18.01_Map集合概述和特點
-
public interface Map<K,V>
鍵值對- 將鍵映射到值的對象!一個映射不能包含重復的鍵!每個鍵最多只能映射到一個值。(通過查看HashMap的源碼,發現Set集合的底層是依賴Map集合的)
-
Map
接口和Collection
接口的不同:-
Map
是雙列的,Collection
是單列的 -
Map
的鍵唯一,Collection
的子體系Set
是唯一的 -
Map
集合的數據結構(算法)只針對鍵有效,跟值無關;Collection
集合的數據結構是針對元素有效
-
18.02_Map集合的功能概述
- a:添加功能
-
V put(K key,V value)
:添加元素。- 如果鍵是第一次存儲,就直接存儲元素,返回null
- 如果鍵不是第一次存在,就用值把以前的值替換掉,返回以前的值
-
- b:刪除功能
-
void clear()
:移除所有的鍵值對元素 -
V remove(Object key)
:根據鍵刪除鍵值對元素,并把值返回
-
- c:判斷功能
-
boolean containsKey(Object key)
:判斷集合是否包含指定的鍵 -
boolean containsValue(Object value)
:判斷集合是否包含指定的值 -
boolean isEmpty()
:判斷集合是否為空
-
- d:獲取功能
-
Set<Map.Entry<K,V>> entrySet()
:獲取所有的鍵值對象的集合 -
V get(Object key)
:根據鍵獲取值 -
Set<K> keySet()
:獲取集合中所有鍵的集合 -
Collection<V> values()
:獲取集合中所有值的集合
-
- e:長度功能
-
int size()
:返回集合中的鍵值對的個數
-
18.03_Map集合的遍歷之鍵找值
- 1.獲取所有鍵的集合
- 2.遍歷鍵的集合,獲取到每一個鍵
- 3.根據鍵找值
Map<String, Integer> map = new HashMap<>();
map.put("第一個", 100); // 自動裝箱
map.put("第二個", 300);
map.put("第三個", 300);
Set<String> set = map.keySet(); //獲取所有的key
//增強for循環遍歷
for (String key : set) {
System.out.println(key + "-->" + map.get(key));
}
//迭代器遍歷
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String key = it.next();
System.out.println(key + "-->" + map.get(key));
}
18.04_Map集合的遍歷之鍵值對對象找鍵和值
- 1.獲取所有鍵值對對象的集合
- 2.遍歷鍵值對對象的集合,獲取到每一個鍵值對對象
- 3.根據鍵值對對象找鍵和值
Map<String, Integer> map = new HashMap<>();
map.put("第一個", 100);
map.put("第二個", 300);
map.put("第三個", 300);
// Map.Entry Entry是Map接口的內部接口,將鍵和值封裝成Entry對象,并存儲在Set集合中。
Set<Map.Entry<String, Integer>> entry = map.entrySet();
// 迭代器
Iterator<Map.Entry<String, Integer>> it = entry.iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> en = it.next();
String key = en.getKey();
Integer value = en.getValue();
System.out.println(key + "-->" + value);
}
// foreach
for (Map.Entry<String, Integer> en : entry) { //父類引用指向子類對象
System.out.println(en.getKey() + "-->" + en.getValue());
}
- 內部接口例子
interface Inter {
interface Inter2 { // 內部接口
public void show();
}
}
class Demo implements Inter.Inter2 { // 實現接口的內部接口
public void show() {}
}
18.05_HashMap集合鍵是Student值是String的案例
// 鍵是Student 值是字符串,代表地址
// 結論: 自定義類,需要重寫 hashCode方法 和 equals 方法
HashMap<Student, String> map = new HashMap<>();
map.put(new Student("張三", 12), "北京");
map.put(new Student("張三", 12), "北京");
map.put(new Student("八戒", 358), "西天");
System.out.println(map); //此時,只有2個元素,張三 和 八戒
// 快速生成 hashCode和equals
// Shift + Alt + s 然后再 h
18.06_LinkedHashMap的概述和使用
-
LinkedHashMap
底層是鏈表實現的可以保證怎么存就怎么取
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("qq", 100);
map.put("yy", 230);
map.put("ww", 100);
System.out.println(map); // 存的順序 和 取的順序是一致的
18.07_TreeMap集合鍵是Student值是String的案例
方案一,不使用比較器
TreeMap<Student, String> tm = new TreeMap<>();
tm.put(new Student("張三", 21), "xxoo");
tm.put(new Student("張三", 25), "xxoo");
tm.put(new Student("趙六", 24), "xoxo");
System.out.println(tm); // 此時,如果自定義對象沒有實現Comparable接口,就會報錯
// TreeMap 會自動排序,比較鍵,鍵對象就必須實現java.lang.Comparable接口
// 自定義對象的 實現 compareTo 方法
@Override
public int compareTo(Student o) {
int num = this.age - o.age; //以年齡為主要條件,姓名為次要條件
return num == 0 ? this.name.compareTo(o.name) : num;
}
方案二,使用比較器
Comparator<Student> comp = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int num = o1.getAge() - o2.getAge();
return num == 0 ? o1.getName().compareTo(o2.getName()) : num;
}
};
TreeMap<Student, String> treeMap = new TreeMap<>(comp);
treeMap.put(new Student("張三", 21), "xxoo");
treeMap.put(new Student("張三", 25), "xxoo");
System.out.println(treeMap);
18.08_統計字符串中每個字符出現的次數
- 需求:統計字符串中每個字符出現的次數
String str = "aaaabbbcccccbcccca";
char[] array = str.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
for (char c : array) {
/*if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}*/
// 可以優化為三目運算符
map.put(c, map.containsKey(c) ? (map.get(c) + 1) : 1);
}
System.out.println(map);
18.09_集合嵌套之HashMap嵌套HashMap
- 集合嵌套之HashMap嵌套HashMap
// 雙列集合--元素一
HashMap<Student, String> map1 = new HashMap<>();
map1.put(new Student("S1", 23), "北京");
map1.put(new Student("S2", 23), "北京");
// 雙列集合--元素二
HashMap<Student, String> map2 = new HashMap<>();
map2.put(new Student("S5", 78), "鄭州");
map2.put(new Student("S8", 45), "天津");
HashMap<Map<Student, String>, String> map = new HashMap<>();
map.put(map1, "第一個元素");
map.put(map2, "第二個元素");
// 遍歷 嵌套雙列集合
for (Map<Student, String> subMap : map.keySet()) {
String s1 = map.get(subMap);
System.out.println("----"+s1+"---");
for (Student stu : subMap.keySet()) {
System.out.println(" " + stu + "--->" + subMap.get(stu));
}
}
18.10_HashMap和Hashtable的區別
-
Hashtable
是JDK1.0版本出現的,是線程安全的,效率低,HashMap
是JDK1.2版本出現的,是線程不安全的,效率高 -
Hashtable
不可以存儲null鍵和null值,HashMap
可以存儲null鍵和null值 - 底層都是哈希算法,都是雙列集合
HashMap<String, String> map = new HashMap<>();
map.put(null, null);
System.out.println(map); // 沒有問題。可以存儲null鍵值
Hashtable<String, String> tab = new Hashtable<>();
tab.put(null, null); //報錯,NullPointerException
18.11_Collections工具類的概述和常見方法講解
- 針對集合操作 的工具類, 類似 操作數組的工具類
Arrays
,其實對于這種工具類的學習,查看文檔即可, 一般都是只有靜態方法(私有了構造方法)。
常用幾個方法
static <T> void sort(List<T> list) 排序List
static <T> int binarySearch(List<?> list,T key) 二分查找List
static <T> T max(Collection<?> coll) 獲取List的最值
static void reverse(List<?> list) 反轉List元素
static void shuffle(List<?> list) 隨機排序List,類似:洗牌
18.12_模擬斗地主洗牌和發牌
- 模擬斗地主洗牌和發牌,牌沒有排序
//買一副撲克
String[] num = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
String[] color = {"方片","梅花","紅桃","黑桃"};
ArrayList<String> poker = new ArrayList<>();
// 拼接花色和數字
for (String s1 : color) {
for (String s2 : num) {
poker.add(s1.concat(s2)); // concat連接兩個字符串
}
}
// 添加大小王
poker.add("大王");
poker.add("小王");
// 洗牌
Collections.shuffle(poker);
// 發牌
ArrayList<String> p1 = new ArrayList<>();
ArrayList<String> p2 = new ArrayList<>();
ArrayList<String> me = new ArrayList<>();
ArrayList<String> dipai = new ArrayList<>(); //底牌,斗地主,要留3張
for (int i = 0; i < poker.size(); i++) {
if (i >= poker.size() - 3) { //將最后3張底牌存儲在底牌集合里
dipai.add(poker.get(i));
} else if ( i % 3 == 0) { //這里的 i%3,應該好好理解一下
p1.add(poker.get(i));
} else if ( i % 3 == 1) {
p2.add(poker.get(i));
} else {
me.add(poker.get(i));
}
}
// 看牌
System.out.println(me);
System.out.println(dipai);
18.13_模擬斗地主洗牌和發牌并對牌進行排序的原理圖解
斗地主.png
18.14_模擬斗地主洗牌和發牌并對牌進行排序的代碼實現
//買一副撲克
String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
String[] color = {"方片","梅花","紅桃","黑桃"};
HashMap<Integer, String> map = new HashMap<>(); //存儲索引和撲克牌
ArrayList<Integer> list = new ArrayList<>(); //存儲索引,為了方便洗牌
// 拼接撲克牌
int index = 0;
for (String s1 : num) {
for (String s2 : color) {
map.put(index, s2.concat(s1));
list.add(index);
index++ ;
}
}
map.put(index, "小王"); list.add(index); //添加大王和小王 以及對應的索引
map.put(++index, "大王"); list.add(index);
// 洗牌,就是洗索引
Collections.shuffle(list);
// 發牌 (就是發索引,TreeSet能自動排序)
TreeSet<Integer> p1 = new TreeSet<>();
TreeSet<Integer> p2 = new TreeSet<>();
TreeSet<Integer> me = new TreeSet<>();
TreeSet<Integer> dipai = new TreeSet<>(); //底牌
for (int i = 0; i < list.size(); i++) {
if (i >= list.size() - 3) {
dipai.add(list.get(i)); //ArrayList有索引,Set沒有索引
} else if ( i % 3 == 0) {
p1.add(list.get(i));
} else if ( i % 3 == 1) {
p2.add(list.get(i));
} else {
me.add(list.get(i));
}
}
// 看牌自己的牌 (這里可以封裝一個專門看牌的方法)
for (Integer i : me) {
System.out.print(map.get(i) + " "); //按照索引,從Map里面取出來對應的牌面值
}
18.15_泛型高級---泛型固定邊界
-
? super E
固定下邊界 -
? extends E
固定上邊界 - 本質都是 父類指向子類對象
集合接口: Collection<E>
方法:
boolean addAll(Collection<? extends E> c)
這里用到了 泛型固定上邊界,意思是 addAll() 方法傳入 Collection 以及子類 都可以。
雙列集合: TreeMap<K,V>
構造方法:
TreeMap(Comparator<? super K> comparator)
例子(注意比較器泛型的類型和TreeSet泛型的類型):
TreeSet<Son> set = new TreeSet<>(new Comparator<Father>() {
@Override
public int compare(Father o1, Father o2) {
int num = o1.getAge() - o2.getAge();
return num == 0 ? o1.getName().compareTo(o2.getName()) : num;
}
});
set.add(new Son("SS1", 21));
set.add(new Son("SS2", 31));
set.add(new Son("SS3", 41));
System.out.println(set);
18.16_四天集合總結
/**
* Collection
* List(存取有序,有索引,可以重復)
* ArrayList
* 底層是數組實現的,線程不安全,查找和修改快,增和刪比較慢
* LinkedList
* 底層是鏈表實現的,線程不安全,增和刪比較快,查找和修改比較慢
* Vector
* 底層是數組實現的,線程安全的,無論增刪改查都慢
* 如果查找和修改多,用ArrayList
* 如果增和刪多,用LinkedList
* 如果都多,用ArrayList
* Set(存取無序,無索引,不可以重復)
* HashSet
* 底層是哈希算法實現
* LinkedHashSet
* 底層是鏈表實現,但是也是可以保證元素唯一,和HashSet原理一樣
* TreeSet
* 底層是二叉樹算法實現
* 一般在開發的時候不需要對存儲的元素排序,所以在開發的時候大多用HashSet,HashSet的效率比較高
* TreeSet在面試的時候比較多,問你有幾種排序方式,和幾種排序方式的區別
* Map
* HashMap
* 底層是哈希算法,針對鍵
* LinkedHashMap
* 底層是鏈表,針對鍵
* TreeMap
* 底層是二叉樹算法,針對鍵
* 開發中用HashMap比較多
*/
END。
我是小侯爺。
在魔都艱苦奮斗,白天是上班族,晚上是知識服務工作者。
如果讀完覺得有收獲的話,記得關注和點贊哦。
非要打賞的話,我也是不會拒絕的。