集合
Collection集合
集合的概念
ArrayList就是一個集合,集合是Java提供的一種容器,可以用來存儲多個資料
集合與數組的差別
1.數組的長度是固定的,集合的長度是可變的
2.數組中存儲的是同一類型的元素,可以存儲基本資料類型。集合中存儲的是對象,且對象的類型可以不一緻,在開發中,一般當對象多的時候,使用集合進行存儲。
集合架構的介紹
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2csIzaU1kMNRVTy0keYhnRzwEMW1mY1RzRapnTtxkb5ckYplTeMZTTINGMShUYfRHelRHLwEzX39GZhh2css2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xyayFWbyVGdhd3LcV2Zh1Wa9M3clN2byBXLzN3btg3Pn5GcuQjNxUDNzUTMxMTNwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
集合的常用功能
Collection<String> collection = new HashSet<>(); //多态
Collection<String> collection = new ArrayList<>();
collection.add("liu");//哪種實作類都可以用
iterator接口的介紹
【注意】iterator是個接口,在collection中的iterator() 方法會傳回iterator的實作類,iterator是Collection接口的方法,是所有集合所共有的方法。
疊代器iterator的代碼實作
//多态 接口 實作類對象
//用接口去接收實作類對象
Iterator<String> it = coll.iterator();
疊代器的實作原理
增強for循環
【注意】collection接口繼承了iterable接口,實作這個接口(iterable)允許對象成為 “foreach” 語句的目标,數組也可以用增強for循環。
泛型
泛型的概念
使用泛型的好處
定義和使用泛型的類
【注意】E隻是一個符号,當然也可以取其他的符号,<>中隻能是引用類型,不支援基本資料類型。
含有泛型的方法
含有泛型的接口
含有泛型的接口有兩種使用方式
泛型通配符
泛型的通配符:
?:代表任意的資料類型
使用方法:
不能建立對象使用
隻能作為方法的參數使用
泛型的上限限定:<? extends E>代表使用的泛型隻能是E類型的子類/本身
泛型的下限限定:<? super E>代表使用的泛型隻能說E類型的父類/本身
資料結構
棧:先進後出
隊列:先進先出
數組:查詢快,增删慢。【注意】個人覺得數組的增删有問題
連結清單:【注意】表中單連結清單和雙連結清單的了解有問題
樹:
樹/二叉樹/排序樹(查找樹)/平衡樹/紅黑樹
List集合
List這個接口就是有序的
介紹
arraylist:List接口的大小可變數組的實作。底層當add,會調用System.arraycopy建立數組。線程不安全(此實作不同步)
linkedlist線程不安全(此實作不同步)
【注意】:pop和push都是對第一個連結清單元素進行操作
Vector可增長的對象數組。是同步的(線程安全的)。
Set
hashset
哈希值
【注意】p1==p2說明比較的是真實位址
System.out.println("重地".hashCode()); //1179395
System.out.println("通話".hashCode()); //1179395
System.out.println("重地"=="通話"); // false
System.out.println("重地".equals("通話")); // false
哈希表
set集合不允許重複的原理
hashset存儲自定義類型元素
【注意】==比較的是位址。equals比較的也是位址,若重寫的話,可不同。
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
linkedhashset的有序性
可變參數
Collections
Collections工具類的方法
comparable接口和comparator接口的不同見上圖。
map集合
map常用子類
map常用方法
【注意】
int v1 = map.remove(key);//自動拆箱 NullPointerException
Integet v2 = map.remove(key);//沒問題
map集合周遊
【注意】hashmap的鍵和值都可以為null。
entry鍵值對對象
HashMap<String, String> map = new HashMap<>();
String put = map.put("liu", "1");
String put1 = map.put("chun", "2");
String put2 = map.put("lei", "3");
Set<Map.Entry<String, String>> entries = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> next = iterator.next();
System.out.println(next.getKey() + " "+next.getValue());
}
System.out.println(map);
for (Map.Entry<String, String> entry : entries) {
}
hashmap存自定義類型
linkedhashmap
hashtable
【注意】key和value都不能為null;線程安全。
jdk9的新特性:對添加元素的優化
debug的使用