Map笔记

Map,是一个接口,是以键值对的方式存储的,并且键是无序且不可重复的。Map和Collection没有什么关系,Map是一对一对的存,而Collection是一个一个的存。

下面有一个子接口:SortedMap,key无序不可重复,但是可以按照大小排序。这个key等同于SortedSet。有一个实现类TreeMap,TreeMap中的key就是一个TreeSet,key要实现Compareble接口,或者单独写个比较器Comparator。

有两个实现类:

HashMap:哈希散列表,其中的key等同于一个Set集合,且要重写hashCode()和equals()。

HashTable:

Map中,如果key重复了,value采用覆盖的方式!!!后面put的覆盖前面的

HashMap默认初始化容量16,加载因子0.75

public class HashMapTest {
    public static void main(String[] args){
        Map map = new HashMap();
        map.put("1", "kobe");
        map.put("2", "kd");
        map.put("3", "tracy");
        map.put("4", "duncan");
        map.put("1", "koo");
        
        //获取所有值
        Iterator it = map.values().iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }
        
        //获取所有键
        Iterator it2 = map.keySet().iterator();
        while(it2.hasNext()){
            Object key = it2.next();
            Object value = map.get(key);
            System.out.println(key + "--->" + value);
        }
        
        //将map转换成set的过程
        Set setEntry = map.entrySet();
        Iterator it3 = setEntry.iterator();
        while (it3.hasNext()){
            System.out.println(it3.next());
        }
    }
}

koo
kd
tracy
duncan
1--->koo
2--->kd
3--->tracy
4--->duncan
1=koo
2=kd
3=tracy
4=duncan

 HashTable

默认初始化容量11,加载因子0.75

Properties是他的一个子类。同样键不能重复,而且重复则覆盖的原则,还有就是键值对都是String类型。

 

SortedMap中的key排序的实现

public class SortedMapTest {

    public static void main(String[] args) {
        Map map = new TreeMap();
        Product p1 = new Product("apple" , 7.0);
        Product p2 = new Product("banana" , 5.0);
        Product p3 = new Product("mango" , 8.0);
        Product p4 = new Product("pear" , 4.0);
        Product p5 = new Product("orange" , 3.5);
        
        map.put(p1, 10.0);
        map.put(p2, 3.0);
        map.put(p3, 9.0);
        map.put(p4, 3.3);
        map.put(p5, 7.2);
        
        Set set = map.keySet();
        Iterator it = set.iterator();
        while (it.hasNext()){
            Product key = (Product)it.next();
            double value = (double)map.get(key);
            System.out.println(key.name + "---" + key.price + "---" + value +"kg");
        }
    }

}

class Product implements Comparable{
    String name;
    double price;
    
    public Product(String name , double price){
        this.name = name;
        this.price = price;
    }
    
    @Override
    public int compareTo(Object o) {
        double p1 = this.price;
        double p2 = ((Product)o).price;
        
        if (p1 > p2)
            return 1;
        else if (p1 < p2)
            return -1;
        else
            return 0;
    }
}

orange---3.5---7.2kg
pear---4.0---3.3kg
banana---5.0---3.0kg
apple---7.0---10.0kg
mango---8.0---9.0kg

posted @ 2016-09-25 21:53  Steve_Nash  阅读(187)  评论(0)    收藏  举报