1:Collection集合与Map集合
Collection集合:元素是孤立存在的,向集合中存储元素采用一个个元素的方式存储,有索引和值。单例集合。
Map集合:每个元素是由健和值两部分组成,通过键可以找到对应的值,健不能重复。双例集合。
2:Map的子类
HashMap<K,V>
1:HashMap底层是哈希表,查询速度很快
2:HashMap是一个无序集合,存和取顺序不一致。
LinkedMap<K,V>
1:是有序的,存和取得顺序一致。
2.1:HashMap<k,v>集合
1,常用方法:
public class HashMap {
public static void main(String[] args) {
// HashMap中的常用方法
java.util.HashMap<String, String> hashMap = new java.util.HashMap<>();
hashMap.put("赵丽颖", "冯绍峰");//在HashMap中添加元素
hashMap.put("赵丽颖2", "冯绍峰2");
hashMap.put("赵丽颖3", "冯绍峰3");
hashMap.remove("赵丽颖3");//删除元素
System.out.println(hashMap);//无序的输出
if(hashMap.containsKey("赵丽颖2")) {
//判断是否包含Key,boolean
String str = hashMap.get("赵丽颖2");//根据key获取Value
System.out.println(str);
}
}
}
{
赵丽颖2=冯绍峰2, 赵丽颖=冯绍峰}//无序的
冯绍峰2
2,HashMap<k,v>的遍历
- 通过键找值得方法:
使用Map集合中的keySet()方法,把Map集合中所有的key取出来,存储到一个Set集合中。
遍历Set集合,后取Map集合中的每一个key
通过Map集合中的get(key)方法找到value
public class HashMap {
@SuppressWarnings("unlikely-arg-type")
public static void main(String[] args) {
// HashMap中的常用方法
java.util.HashMap<String, String> hashMap = new java.util.HashMap<>();
hashMap.put("赵丽颖", "冯绍峰");//在HashMap中添加元素
hashMap.put("赵丽颖2", "冯绍峰2");
hashMap.put("赵丽颖3", "冯绍峰3");
Set<String> set = hashMap.keySet();//keySet()方法获取到每一个key值
Iterator<String> it = set.iterator();//迭代遍历
while(it.hasNext()) {
String next = it.next();
String st = hashMap.get(next)//这个next取出来的是key,根据key取出来value值
System.out.println(st);
}
for(String st:set) {
//增强for循环遍历
String val = hashMap.get(st);
System.out.println(val);
}
}
}
HashMap的Entry存储的是两者之间的关系,如结婚证。
- 通过HashMap的entrySet()方法
1:使用HashMap的entrySet()方法,把HashMap集合的Entry对象取出来,存储到一个Set集合中。
2:遍历Set集合,获取每一个Entry对象。
3:通过Entry对象的getKey(),getValue()方法取得键和值。
public class HashMap {
@SuppressWarnings("unlikely-arg-type")
public static void main(String[] args) {
// HashMap中的常用方法
java.util.HashMap<String