一、Map概述
1、概述
将键映射到值的对象。一个映射不能包含重复的键;每个键最多只能映射一个值。
2、特点
Map:一次添加一对元素。Collection:一次添加一个元素。
Map也称为双列集合,Collection集合称为单列集合。
其实map集合中存储的就是键值对。
map集合中必须保证键的唯一性。
二、Map中常用的方法:
1,添加。
value put(key,value):返回前一个和key关联的值,如果没有返回null.
2,删除。
void clear():清空map集合。
value remove(key):根据指定的key删除这个键值对。
3,判断。
boolean containsKey(key):
boolean containsValue(value):
boolean isEmpty();
4,获取。
value get(key):通过键获取值,如果没有该键返回null。
当然可以通过返回null,来判断是否包含指定键。
int size():获取键值对的个数。
三、Map常见的三个子类:
1、Hashtable :
内部结构是哈希表,是同步的。不允许null作为键,null作为值。
2、HashMap :
内部结构是哈希表,不是同步的。允许null作为键,null作为值。
两个常用方法介绍:
返回此映射中包含的键的Set 视图。
2)publicSet<Map.Entry<K,V>>entrySet()
返回此映射中包含的映射关系的Set 视图。
3)HashMap的示例代码如下:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import cn..Student;
publicclass HashMapDemo {
publicstaticvoid main(String[] args) {
HashMap<Student,String> hm = new HashMap<Student,String>();
hm.put(new Student("lisi",38),"北京");
hm.put(new Student("zhaoliu",24),"上海");
hm.put(new Student("xiaoqiang",31),"沈阳");
hm.put(new Student("wangcai",28),"大连");
hm.put(new Student("zhaoliu",24),"铁岭");
Set<Student> keySet = hm.keySet();
Iterator<Student> it = keySet.iterator();
while(it.hasNext()){
Student key = it.next();
String value = hm.get(key);
System.out.println(key.getName()+":"+key.getAge()+"---"+value);
}
}
}
3、TreeMap :
内部结构是二叉树,不是同步的。可以对Map集合中的键进行排序。
经常用于此类的两个方法与HashMap相同。
注意:
由于TreeMap要对存入里面的对象进行排序,所以对于将要存入里面的对象一定要实现Comparable接口,覆盖其中的compareTo()方法,或者在构造TreeMap的时候就手动的指定一个构造器,否则对象将无法存入。
对于TreeMap及其entrySet()方法的演示如下:
publicclass TreeMapDemo {
publicstaticvoid main(String[] args) {
TreeMap<Student,String> tm = new TreeMap<Student,String>(new ComparatorByName());
tm.put(new Student("lisi",38),"北京");
tm.put(new Student("zhaoliu",24),"上海");
tm.put(new Student("xiaoqiang",31),"沈阳");
tm.put(new Student("wangcai",28),"大连");
tm.put(new Student("zhaoliu",24),"铁岭");
Iterator<Map.Entry<Student, String>> it =tm.entrySet().iterator();
while(it.hasNext()){
Map.Entry<Student,String> me = it.next();
Student key = me.getKey();
String value = me.getValue();
System.out.println(key.getName()+":"+key.getAge()+"---"+value);
}
}
}