Map
key ---value 单向
Map具有映射关系,以键值对方式存储
key不能重复,可以是任何类型
1.注意Map集合添加方法是put(key,value)
key valus是对象,不能放基本类型
Map map=new HashMap()
添加数据
// map.put(Object k,Object v);
map.put("Aa","aaaa");
map.put("Aa",new Person("tom","aaa"));
map.putAll(Map w);//添加集合
如果map.put(aa,"aaa");
map.put(aa,"aaa");
那么第一个返回的是null;
会覆盖(key值不能重复),那么aa就没有对应关系这返回null;
Map是java中的接口,Map.Entry是Map的一个内部接口。
Map提供了一些常用方法,如keySet()、entrySet()等方法,keySet()方法返回值
Map中key值的集合;entrySet()的返回值也是返回一个Set集合,此集合的类型为
Map.Entry。(遍历的时候就知道了,要掌握)
Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry<K,V>。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。
Map.Entry()中才有getkey() getvalue()方法.
Map集合的遍历;
只有实现的collection集合才有iterator方法,比如List和se接口;而Map接口不能使用iterator方法,需要现获取set视图,即Set set = map.keySet();
set就可以使用了。
Map集合遍历的方法
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("1", "value1");
map.put("2", "value2");
map.put("3", "value3");
//第一种:普遍使用,二次取值
System.out.println("通过Map.keySet遍历key和value:");
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
}
//第二种
System.out.println("通过Map.entrySet使用iterator遍历key和value:");
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第三种:推荐,尤其是容量大时
System.out.println("通过Map.entrySet遍历key和value");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}
//第四种
System.out.println("通过Map.values()遍历所有的value,但不能遍历key");
for (String v : map.values()) {
System.out.println("value= " + v);
}
}
可以用Map的values方法 ,但得到的是Countion集合.
===================================Map的子类==========================================
Hashtable:内部结构是哈希表,是同步的(不支持)
|---Properties:用来存储键值队型的配置文件信息,可以和Io技术相结合.
HashMap: 内部是哈希表,是不同步的(支持key=nul,value=null)
自定义存储对象:
Map<HashMap自定义存储对象, String> map=new HashMap<HashMap自定义存储对象, String>();
map.put(new HashMap自定义存储对象("张三",11), "小学");
map.put(new HashMap自定义存储对象("张三",11), "中学");
map.put(new HashMap自定义存储对象("李四",12), "小学");
map.put(new HashMap自定义存储对象("王五",13), "大学");
map.put(new HashMap自定义存储对象("赵六",18), "大学");
Iterator<Entry<HashMap自定义存储对象, String>> it =map.entrySet().iterator();
while(it.hasNext()){
//it.next()是map.entrySet().....所以要转为Entry类型。
Entry<HashMap自定义存储对象, String> en=it.next();
//key是HashMap自定义存储对象所以要装换,否则拿到的是一个地址
HashMap自定义存储对象 ha=en.getKey();
//
System.out.println(ha.getName()+":"+ha.getAge()+"========"+en.getValue());
}
TreeMap: 内部是二叉树,是不同步,可以对Map集合中的键进行排序