标签:get dHash 创建 ring while null none 实现类 rop
Map常用子类:
Map常用方法::
注:
Map.Entry<K,V>:在Map接口中有一个内部接口Entry,当Map集合创建时,内部就会创建一个Entry对象,用于记录键和值对象(保存键和值的映射关系)
1 public class demo03 { 2 3 public static void main(String[] args) { 4 5 Map<String, String> map = new HashMap<>(); 6 7 //1.存入键值对 8 map.put("key1", "value1"); 9 map.put("key2", "value2"); 10 map.put("key3", "value3"); 11 map.put("key4", "value4"); 12 13 System.out.println(map); 14 15 //2.删除对应key的键值对 16 map.remove("key1"); 17 System.out.println(map); 18 19 //3.获得对应key的value值 20 System.out.println(map.get("key3")); 21 22 //4.判断是否包含对应key的键值对 23 System.out.println(map.containsKey("key5")); 24 25 //5.遍历Map中的所有key,方法一 26 Set<String> set = map.keySet(); 27 28 Iterator<String> iterator = set.iterator(); 29 while (iterator.hasNext()) { 30 System.out.println(iterator.next()); 31 } 32 33 //遍历Map中的所有key,方法二 34 // for (String s: map.keySet() 35 // ) { 36 // System.out.println(s); 37 // } 38 39 //6.遍历Map中所有的键值对对象,方法一 40 Set<Map.Entry<String,String>> set2 = map.entrySet(); 41 42 Iterator<Map.Entry<String,String>> iterator2 = set2.iterator(); 43 while (iterator2.hasNext()){ 44 System.out.println(iterator2.next()); 45 } 46 47 //遍历Map中所有的键值对对象,方法二 48 // for (Map.Entry<String,String> entry: map.entrySet() 49 // ) { 50 // System.out.println(entry); 51 // } 52 53 } 54 }
使用HashMap来存储自定义类型:
1 public class demo04 { 2 3 public static void main(String[] args) { 4 5 HashMap<Person,String> hashMap = new HashMap<>(); 6 7 hashMap.put(new Person("wzh",24),"person1"); 8 hashMap.put(new Person("wzh",24),"person2"); 9 hashMap.put(new Person("wxl",23),"person3"); 10 hashMap.put(new Person("wzl",23),"person4"); 11 12 for (Map.Entry<Person,String> entry: hashMap.entrySet() 13 ) { 14 System.out.println(entry); 15 } 16 17 /** 18 * 输出 19 * Person{name=‘wzh‘, age=24}=person2 20 * Person{name=‘wzl‘, age=23}=person4 21 * Person{name=‘wxl‘, age=23}=person3 22 */ 23 } 24 }
使用LinkedHashMap:存取顺序相同
1 public class demo05 { 2 3 public static void main(String[] args) { 4 5 HashMap<String,String> hashMap = new HashMap<>(); 6 7 hashMap.put("key3","value3"); 8 hashMap.put("key2","value2"); 9 hashMap.put("key4","value4"); 10 hashMap.put("key1","value1"); 11 12 //存取顺序不相同 13 System.out.println(hashMap); //{key1=value1, key2=value2, key3=value3, key4=value4} 14 15 LinkedHashMap<String,String> linkedHashMap = new LinkedHashMap<>(); 16 17 linkedHashMap.put("key3","value3"); 18 linkedHashMap.put("key2","value2"); 19 linkedHashMap.put("key4","value4"); 20 linkedHashMap.put("key1","value1"); 21 22 //存取顺序相同 23 System.out.println(linkedHashMap); //{key3=value3, key2=value2, key4=value4, key1=value1} 24 } 25 }
集合中新增of方法:
标签:get dHash 创建 ring while null none 实现类 rop
原文地址:https://www.cnblogs.com/zhihaospace/p/12117276.html