Java集合中Map

Map

Map将键映射到值的对象,不能包含重复的键,每个键最多只能映射到一个值。
这个接口取代了Dictionary类,Dictionary类是一个完全抽象的类,而不是一个接口。
Map接口提供了三个集合视图,允许将Map的内容视为一组键、一组值或一组键值映射。map的顺序定义为映射集合视图上的迭代器返回其元素的顺序。一些map实现,比如TreeMap类,对它们的顺序做了特定的保证;其他的类,比如HashMap类,则不然。
注意:如果使用可变对象作为映射键,则必须谨慎。当对象是map中的键时,如果对象的值以影响equals比较的方式更改,则不指定映射的行为。



一、Map


/*
* Map: 无序,可重复。用于保存具有映射关系的数据,保存的是两组值
*   key~value:之间存在单向一对一关系,通过key可以找到唯一的value值
*   key和value都可以是任意引用类型对象
*   允许存在value值为null,但只允许存在一个key为null
*   value可重复,key不可重复
* Map和集合操作基本一致
*
* 常用方法:
*   Object put(Object key, Object value): 向map中添加键值对
*   void clear(): 清空
*   int size(): 所添加元素个数
*   boolean isEmpty(): 判断是否为空
*   Object get(Object key): 根据key,获取value
*
*   Collection values(): 获取map中所有value值,以集合形式返回
*   boolean containsKey(Object key): 判断是否包含某个key
*   boolean containsValue(Object value): 判断是否包含某个value
*
*   Set keySet(): 返回map中的所有key,以Set集合形式返回
*   Set entrySet(): 返回map中的键值对映射(key=value),以Set集合形式返回
*   V remove(Object key): 根据key删除指定映射关系
*
* map不能直接遍历,可通过keySet等方法进行间接遍历
* */

二、HashMap


public class _01_Map {

    public static void main(String[] args) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        hashMap.put("A", "one");
        hashMap.put("B", "two");
        hashMap.put("C", "three");
        hashMap.put(100, "a coding day");
        hashMap.put('A', 1000);
        hashMap.put(65, 1001);
        hashMap.put(64, 644);
        hashMap.put("'A'", 1002);
        hashMap.put("A", 3000);
        // map中只能有一个key为null
        hashMap.put(null, null);
        System.out.println(hashMap.size()); // 8 3000覆盖one,size-1

        // 获取“100”的hashCode()值,进行hash算法得到数组下标
        // 用该对象调用equals方法和数组中链表的所有对象的key比较
        // 此对象 为字符串 “100”,map中没有,只有Integer的100。为false
        System.out.println(hashMap.containsKey("100")); // false
        // value只能依次遍历比较
        // “one” 的key 和1000的key相同,被1000覆盖。key=A 对应 value=1000
        System.out.println(hashMap.containsValue("one")); // false
        System.out.println(hashMap.containsValue("two")); // true

        // 和containsKey()方法基本一致,通过key找到对象后,获取其value值
        System.out.println(hashMap.get(65));
        System.out.println("----------------");

        // 获取所有value及遍历
        Collection c = hashMap.values();
        for (Object o : c) {
            System.out.println(o);
        }
        System.out.println("hashMap.remove(100)");
        System.out.println(hashMap.remove(100));
        System.out.println("----------");

        // 返回map中的key
        Set set = hashMap.keySet();
        for (Object o : set) {
            System.out.println(o);
        }

        System.out.println("----------");
        // 返回map中的键值对映射(key=value)
        Set entrys = hashMap.entrySet();
        for (Object o : entrys) {
            System.out.println(o);
        }
        System.out.println("----------");
        for (Object object : entrys) {
            // Map中的Entry类型
            Map.Entry entry = (Map.Entry) object;
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

/*
 // HashMap中向map中添加键值对的put()方法源码
 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
 // 获取key的hashCode()值,进行hash算法得到数组下标
 static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
 // 添加元素,每个数组所在位置对应一个链表
 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0) // 数组(表)为空
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null) // 把 键值对 保存到该数组中
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k)))) // 用该对象调用equals方法和数组中链表的所有对象的key比较
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
* */

/*
* 特殊的Map: 强制规定键值对都必须是字符串
*   java.util.Properties
* */
public class _02_Map_Properties {

    public static void main(String[] args) {
        Properties properties = new Properties();
        properties.setProperty("driver","xxx");
        properties.setProperty("username","root");

        String driver = properties.getProperty("driver");
        System.out.println(driver);

        // getProperty()方法第二个参数为指定默认值
        // 如果根据password这个key能找到对应的value,就获取对应value
        // 找不到则返回指定默认value
        System.out.println(properties.getProperty("password","admin"));
    }
}

三、SortMap


/*
* SortMap 是接口,子实现类是TreeMap,元素必须有序,会按照某个规定进行排序
*   按照key进行排序
*   实现排序原因:
*       1 被添加元素,实现了Comparable接口
*       2 按照需求,编写比较器类,该比较器类必须实现Comparable接口
* */
public class _03_SortedMap {

    public static void main(String[] args) {
        TreeMap<Object, Object> treeMap = new TreeMap<>();
        treeMap.put(1,11);
        treeMap.put(12,1);
        treeMap.put(15,21);
        treeMap.put(10,31);

        // Integer实现了Comparable接口,默认升序
        Set key = treeMap.keySet(); // key
        for (Object o : key) {
            System.out.println(o + ": " + treeMap.get(o));
        }
        System.out.println("-----------");
        Set entrys = treeMap.entrySet(); // 键值对映射(key=value)
        for (Object entry : entrys) {
            System.out.println(entry);
        }
        System.out.println("-----------");
        Collection col = treeMap.values(); // value
        for (Object o : col) {
            System.out.println(o);
        }
        System.out.println("-----------");

        // 更改为降序
        TreeMap<Object, Object> map = new TreeMap<>(new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                Integer i1 = (Integer) o1;
                Integer i2 = (Integer) o2;
                return i2 - i1;
            }
        });

        map.put(1,11);
        map.put(12,1);
        map.put(15,21);
        map.put(10,31);

        Set entrys2 = map.entrySet();
        for (Object o : entrys2) {
            System.out.println(o);
        }
    }
}

/*
 // TreeMap中get方法源码
 public V get(Object key) {
        Entry<K,V> p = getEntry(key);
        return (p==null ? null : p.value);
    }
 // 核心是通过compareTo()方法比较key来返回value
 final Entry<K,V> getEntry(Object key) {
        // Offload comparator-based version for sake of performance
        if (comparator != null)
            return getEntryUsingComparator(key);
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) key;
        Entry<K,V> p = root;
        while (p != null) {
            int cmp = k.compareTo(p.key);  // 调用compareTo()方法比较
            if (cmp < 0)
                p = p.left;
            else if (cmp > 0)
                p = p.right;
            else
                return p;
        }
        return null;
    }
* */

// TreeMap应用demo
public class _04_SortedMap {

    public static void main(String[] args) {

        TreeMap<Object, Object> treeMap = new TreeMap<>();

        Product potato = new Product("土豆", 2.2);
        Product cabbage = new Product("白菜", 1.8);
        Product tomato = new Product("西红柿", 3.5);
        Product beef = new Product("牛肉", 52.2);

        // key表示购买商品,value表示数量
        treeMap.put(potato,2);
        treeMap.put(tomato,1);
        treeMap.put(cabbage,3);
        treeMap.put(beef,3);

        Set entrys = treeMap.entrySet();
        for (Object entry : entrys) {
            System.out.println(entry);
        }
        System.out.println("------------");

        Set key = treeMap.keySet();
        for (Object o : key) {
//            System.out.println(o + ", " + treeMap.get(o) + " KG");
            Product product = (Product) o;
            String name = product.getName();
            double price = product.getPrice();
            int value = (Integer) treeMap.get(o); // get返回Object对象,若用int存放,应类型转换
            System.out.println(name+"/"+price+"每KG"+", 购买了 "+value+
                    "KG, 共:"+(price*value)+"元");
        }
    }
}

class Product implements Comparable{
    private String name;
    private double price;

    @Override
    public String toString() {
        return "name: "+name+", price: "+price;
    }

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    // 商品类使用price作排序属性
    // treeMap是靠compareTo方法决定是否唯一性,他的get()方法是跟库key调用compareTo方法
    // 和每个key进行比较,返回0说明相等,就获取value值
    @Override
    public int compareTo(Object o) {
        Product other = (Product) o;
        // return other.getPrice() - this.price; // 相减返回的是double类型,该方法需要返回int
        // 因此使用if判断
        // this表示当前添加对象,other表示已添加对象
        // this.price - other.price > 0 ,则放后面,< 0 放前面 。= 0 覆盖
        if (other.getPrice() > this.price){
            return -1;
        } else if (other.getPrice() < this.price){
            return 1;
        } else {
            return 0;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值