java使用数组实现简单的Map


/**
 *  (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));
    }

}

}

输出结果
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值