参考: Thinking in Java
简介
Map的数据保存是以键值对的形式进行数据的保存,这种键值对的关联形式又叫映射表,或者说关联数组,那么如何用一个简单的数组来实现Map的基本形式.
代码
/**
* @description 关系数组,又称为映射表
* 这是Map实现的基本思想,即用键值对的形式保存数据
* @author paul
* @date 2017年6月14日 下午3:06:59
* @update 2017年6月14日 下午3:06:59
* @version V1.0
*/
public class AssociativeArray<K, V> {
private Object[][] pairs;
//关联数组的下标
private int index;
public AssociativeArray(int length) {
pairs = new Object[length][2];
}
/**
* @param key
* @param value
* @description 放入元素
* @author paul
* @date 2017年6月14日 下午3:22:25
* @update 2017年6月14日 下午3:22:25
* @version V1.0
*/
public void put(K key, V value) {
if (index >= pairs.length)
throw new ArrayIndexOutOfBoundsException();
pairs[index++] = new Object[]{key, value};
}
/**
* @param key
* @return
* @description 根据key值取出元素
* @author paul
* @date 2017年6月14日 下午3:22:33
* @update 2017年6月14日 下午3:22:33
* @version V1.0
*/
@SuppressWarnings("unchecked")
public V get(K key) {
//遍历关联数组,找到key相等的,返回value
for (int i=0; i<pairs.length; i++)
if (key.equals(pairs[i][0]))
return (V)pairs[i][1];
return null;//没有找到返回null
}
/**
* @param key
* @return
* @description 是否有某个主键
* @author paul
* @date 2017年6月16日 下午10:46:46
* @update 2017年6月16日 下午10:46:46
* @version V1.0
*/
public boolean contains(K key) {
for (int i=0; i<pairs.length; i++)
if (key.equals(pairs[i][0]))
return true;
return false;
}
/**
* @return
* @description 是否为空
* @author paul
* @date 2017年6月16日 下午10:48:15
* @update 2017年6月16日 下午10:48:15
* @version V1.0
*/
public boolean isEmpty() {
return pairs.length == 0;
}
/**
*
* @description 清空元素
* @author paul
* @date 2017年6月16日 上午9:00:47
* @update 2017年6月16日 上午9:00:47
* @version V1.0
*/
public void clear() {
for (int i=0; i<pairs.length; i++) {
pairs[i][0] = null;
pairs[i][1] = null;
}
}
//重写toString
public String toString() {
StringBuffer result = new StringBuffer("{");
for (int i=0; i<index; i++) {
result.append(pairs[i][0].toString());
result.append(":");
result.append(pairs[i][1].toString());
if (i < index - 1) {
result.append(",");
} else {
result.append("}");
}
}
return result.toString();
}
public static void main(String[] args) {
AssociativeArray<String, String> aa = new AssociativeArray<String, String>(2);
aa.put("1", "语文");
aa.put("2", "English");
System.out.println(aa.index);
System.out.println(aa.toString());
}
}