Map接口:键值对
- Map接口的集合中不能包含重复的键,值可以重复;每个键只能对应一个值
- Map接口和Collection接口的区别在于collection接口的集合中存储单列数据(单身汉),map接口的集合中存储双列数据(夫妻关系)
- map和collection接口没有继承关系
2个常用集合
- HashMap: 存取无序,需要重写键的hashCode()方法、equals()方法来保证键唯一
- LinkedHashMap:是HashMap的子类,链表结构保证存储有序
3个常用方法
- V put(K,V),K作为键的对象,V作为值的对象。返回值可以用Integer接收
添加重复键时,不会报错,但是会覆盖原始值
返回值一般返回null,只有当存储重复键的时候,会返回被覆盖之前的值
private static void function() {
// TODO Auto-generated method stub
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("zheng", 8);
map.put("gao", 4);
Integer j = map.put("song", 2);
Integer i = map.put("zheng", 9);
System.out.println(map);
System.out.println(i);
System.out.println(j);
}
输出:
{song=2, gao=4, zheng=9}
8
null
- V get(K),通过键对象获取值对象
查询无此键时返回null
private static void function_1() {
// TODO Auto-generated method stub
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("zheng", 8);
map.put("gao", 4);
Integer i = map.get("zheng");
Integer j = map.get("song");
System.out.println(i);
System.out.println(j);
}
输出:
8
null
- V remove(K)
移除键值对,返回被移除之前的值
无此键时,返回空,同时也不做移除
遍历方法:keySet()
得到Map集合中所有的键,返回set集合,然后用迭代器或者增强for去遍历
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
//Map集合的遍历
// 利用键获取值
// Map接口中定义方法keySet
// 所有的键,存储到Set集合
public class MapDemo {
public static void main(String[] args) {
/*
* 1.调用map集合方法keySet,所有键存储到set集合中
* 2.遍历set集合,获取set集合所有元素(map中的键)
* 3.调用map集合方法get,通过键获取到值
*/
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("zheng", 18);
map.put("gao", 30);
Set<String> set = map.keySet();
// 这里的set是hashset的一个内部类,$是内部类的意思
System.out.println(set.getClass());
Iterator<String> it = set.iterator();
System.out.println("-----------迭代器遍历-----------");
while(it.hasNext()) {
String key = it.next();
Integer value = map.get(key);
System.out.println(key+"..."+value);
}
System.out.println("-----------增强for遍历-----------");
for(String key : set) {
Integer val = map.get(key);
System.out.println(key+"..."+val);
}
}
}