文章目錄
- Map
- 1.Map的定義
- 2.Map的常見方法
- 3.Map的注意事項
- 4.代碼示例
- Set
- 1.Set的定義
- 2.Set的常用方法
- 3.Set的注意事項
- 4.代碼示例
Map
1.Map的定義
Map中存盤的是Key-Value的鍵值對,將鍵映射到值的物件,映射不能包含重復的鍵,每個鍵最多可以映射到一個值
2.Map的常見方法

3.Map的注意事項
(1)put是根據一個函式來存放的,并非按順序存放
(2)Map不能存放相同的鍵,如果存放,則會更新為最新的value
(3)Map不能使用迭代器進行列印
(4)Map中的key,value均可以為null
(5)Map是一個介面,不能直接實體化物件,只能實體化TreeMap或者HashMap
(6)Map中存放鍵值對的key是唯一的,value是可以重復的
4.代碼示例
HashMap<String,String> map = new HashMap<>();
//1. put存放元素
map.put("張三","java");
map.put("李四","c++");
map.put("王五","python");
System.out.println(map);
//2.get,獲取key對應的value
String str1 = map.get("王五");
System.out.println(str1);
//3.getOrDefault,回傳key對應的value
String str2 = map.getOrDefault("李四","php");
System.out.println(str2);
String str3 = map.getOrDefault("張田","js");
System.out.println(str3);
//4.remove,洗掉key對應的映射關系
map.remove("王五");
System.out.println(map);
//5.再次put
map.put("小明","k");
map.put("李四","yu");
map.put("小紅","k");
System.out.println(map);
//6.keySet, 回傳key的所有不重復集合
Set<String> set = map.keySet();
System.out.println(set);
//7.values,回傳所有value的可重復集合
Collection<String> coll = map.values();
System.out.println(coll);
//8.entrySet,回傳所有的keyValue映射
Set<Map.Entry<String,String>> set2 = map.entrySet();
for(Map.Entry<String,String> entry : set2){
System.out.println(entry.getKey()+" "+entry.getValue());
}
//9.containsKey
System.out.println(map.containsKey("小紅"));
//10.containsValue
System.out.println(map.containsValue("java"));
//11.size
System.out.println(map.size());
//12.isEmpty
System.out.println(map.isEmpty());
運行結果:

Set
1.Set的定義
Set是繼承來自Collection的介面類,Set中存放了Key
2.Set的常用方法

3.Set的注意事項
(1)Set的底層使用Map來實作的,其使用key與Object的一個默認物件作為鍵值對插入到Map中
(2)Set最大的功能就是去重
4.代碼示例
HashSet<String> set = new HashSet<>();
//1.add添加元素
set.add("one");
set.add("two");
set.add("three");
set.add("four");
System.out.println(set);
//2.contains,判斷是否包含元素
System.out.println(set.contains("three"));
//3.回傳迭代器
Iterator<String> it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//4.洗掉集合中的元素
System.out.println(set.remove("two"));
System.out.println(set);
//5.size,獲取元素個數
System.out.println(set.size());
//6.isEmpty,判斷是否為空
System.out.println(set.isEmpty());
//7.toArray
Object [] array = set.toArray();
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
Collection<String> coll = new HashSet<>();
coll.add("one");
coll.add("three");
//8.containsAll(Collection<?>)
System.out.println(set.containsAll(coll));
//9.addAll(Collection<? extends E> c)
Collection<String> co = new HashSet<>();
co.add("one");
co.add("four");
co.add("two");
System.out.println(set.addAll(co));
System.out.println(set);
運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/267069.html
標籤:java
