/**
* (1) 自反性:就是说a.equals(a)必须为true。
(2) 对称性:就是说a.equals(b)=true的话,b.equals(a)也必须为true。
(3) 传递性:就是说a.equals(b)=true,并且b.equals(c)=true的话,a.equals(c)也必须为true。
通过改写key对象的equals和hashCode方法,我们可以将任意的业务对象作为map的key(前提是你确实有这样的需要)。
* @author TanZhiLin
*
*/
public class Map<K,V> {
private static int length = 128; //数组初始长度
private static int index; //数组索引
private static Object K[] = null;
private static Object V[] = null;
/*public Map() {
K = new Object[length]; //扩大原来的2倍;
V = new Object[K.length];
}*/
static {
K = new Object[length]; //扩大原来的2倍;
V = new Object[K.length];
}
/**
* 清空所有数据
*/
public static void clear() {
for (int i = 0; i < index; i++) {
K[i] = null;
V[i] = null;
}
//将索引设置为0
index = 0;
}
public static void put(Object key,Object value) {
if(key != null) {
K[index] = key;
V[index] = value == null || value == "" ? null : value;
}
index++;
}
public static Object get(Object key) {
if(key == "") {
return null;
}
int result;
if((result = lineSearch(K, key)) < 0) {
return null;
}
return V[result];
}
/**
* Map实际存储的数据长度
* @return
*/
public static int length() {
return index - 1;
}
/**
* 线性查找
* @param K found
* @param key
* @return
*/
public static int lineSearch(Object[] K,Object key) {
boolean flag = false;
for (int i = 0; i < index ; i++) {
if(K[i].equals(key)) {
//对比HashCode码是否一致
if( K[i].hashCode() == key.hashCode() ) {
flag = true;
return i;
}
if(i == index && !flag) {
throw new NullPointerException("Did not find the key, you can try to add the change key in the get");
}
}
}
return -1;
}
}
测试用例:
public class Test{
public static void main(String[] args) {
Map.put(1, "张三");
Map.put(2, "李四");
Map.put(3, "王五");
Map.put(4, "赵六");
Map.put(5, "小七");
Map.put("free", 666);
Map.put("free02", 777);
System.out.println(Map.get("f1ree"));
System.out.println(Map.get("free02"));
System.out.println( Map.length());
//清空
//Map.clear();
System.out.println( Map.length());
for (int i = 1; i < Map.length(); i++) {
System.out.println(Map.get(i));
}
}
}
输出结果