集合
1.概念:
看做一種容器,用來存儲對象信息,所有的集合都位於java.util包下。
2.數組和集合的區別
1)數組存儲的是相同的數據類型,集合可以存儲不同的數據類型。
2)數組可以存儲基本類型的數據,也可以存儲對象,集合只能存儲對象。
3)數組長度是不可變化的,一旦確定,只能存儲固定個數的元素;集合可以存儲數量不確定的
數據。
3.集合中包含的主要接口:java集合中有兩個根接口Collection和Map派生出來的。
(1)Collection接口
1)List接口:存儲有序的、可重複的元素。(底層實現是使用數組)
實現類 | 特點 |
---|---|
ArrayList | 主要的實現類 |
LinkList | 鏈表的實現方式,主要進行頻繁的刪除查找操作 |
Vector | 線程安全的動態數組 |
2)Set接口:存儲無序的,不可重複的元素。(添加相同的數據只存儲一份)
實現類 | 特點 |
---|---|
HashSet | 主要的實現類 |
LinkedHashSet | HashSet的一個子類,根據元素的hashcode值來決定存儲的位置,也是使用鏈表維護元素的順序(性能低於hashSet) |
TreeSet | 是SortedSet 接口的實現類,可以保證元素處於排序狀態,默認是自然排序 |
自然排序:TreeSet會調用集合元素的compareTo(Object)方法比較元素的大小關係,然後將元素升序排列。
3)Queue接口(隊列)
(2)Map接口:存儲的數據是鍵值對<key,value>
key:是不能重複的,使用Set來存儲
value:是可以重複的,使用Collection來存儲
實現類 | 特點 |
---|---|
HashMap | 主要的實現類 |
LinkedHashMap | … |
TreeMap | … |
Hashtable | 它的子類(Properties:鍵值對都是String類型) |
層級關係如下:
集合常用方法代碼塊:
Collection coll = new ArrayList();
//1.size()返回集合中元素的個數
coll.size();
//2.add(Object obj)添加元素
coll.add(123);
coll.add(123);
coll.add("a");
coll.add(new Date());
System.out.println(coll.size());
System.out.println(coll);
//3.addAll(Collection coll):將集合中 的所有元素添加到當前集合
//Arrays有個asList(T ...a);方法將數組轉化爲集合
Collection coll1 = Arrays.asList(1,2,3,4,5);
coll.addAll(coll1);
System.out.println(coll);
//4.isEmpty():判斷集合是否爲空
System.out.println(coll.isEmpty());
//5.clear()清空集合中的元素
coll.clear();
System.out.println(coll.isEmpty());
還有下面
Collection coll = new ArrayList();
coll.add(123);
coll.add("tina");
coll.add(new Date());
coll.add("a");
coll.add(new Person("eric",20));
System.out.println(coll);
//6.contains(Object o):判斷集合中是否包含指定元素
boolean b1 = coll.contains(123);
System.out.println(b1);
//如果存入集合的元素是自定義對象,需要重寫hashCode(),equals() 方法
boolean b2 = coll.contains(new Person("eric", 20));
System.out.println(b2);
//7.remove():移除集合中的元素
boolean b3 = coll.remove("a");
System.out.println(b3);
System.out.println(coll);
//8.removeAll(Collection coll):從當前集合刪除另外一個集合
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add("a");
//coll.removeAll(coll1);
System.out.println(coll);
//9.toArray():將集合轉化爲Object類型數組
Object[] array = coll.toArray();
System.out.println("-----------------");
for (Object object : array) {
System.out.println(object);
}
System.out.println("---------------------");
//10.iterator()迭代器:可以實現對集合的遍歷
//迭代器是一種設計模式,它是一個輕量級對象
//Iterator是一個接口,是集合的迭代器
//hasNext():判斷集合中是否存在下一個元素,如果有:返回true
//next():返回集合裏的下一個元素
Iterator iterator = coll.iterator();
while(iterator.hasNext()) {
Object object = iterator.next();
System.out.println(object);
}
(3)遍歷集合方法
1.使用迭代器
2.使用for循環
3.使用增強for循環,其底層實現是使用迭代器
4.將集合轉化爲數組(toArray),再進行遍歷