1.集合概述
- 集合:集合是java中的一種容器,可用來(lái)存儲(chǔ)多個(gè)數(shù)據(jù)。
- 集合與數(shù)組的對(duì)比
| 數(shù)組 | 集合 |
|---|---|
| 長(zhǎng)度固定 | 長(zhǎng)度可變 |
| 存儲(chǔ)同一類型元素,可以存儲(chǔ)基本數(shù)據(jù)類型數(shù)值 | 存儲(chǔ)對(duì)象,而且對(duì)象類型可以不一致,在開發(fā)中一般對(duì)象多的時(shí)候,使用集合進(jìn)行存儲(chǔ)。 |
集合框架

Collection接口
List接口:
- 有序的集合(存儲(chǔ)和取出元素順序相同)
- 允許存儲(chǔ)重復(fù)的元素
- 有索引,可以用普通的for循環(huán)遍歷
ArrayList接口:底層是數(shù)組實(shí)現(xiàn)的,查詢快、增刪慢。
LinkerList接口:底層是數(shù)組實(shí)現(xiàn)的,查詢慢、增刪快。
set接口:
- 不允許存儲(chǔ)重復(fù)的元素
- 沒(méi)有索引(不能使用普通的for循環(huán)遍歷)
collection:
定義的是所有單例集合中共性的方法,搜友單機(jī)和都可以使用共性的方法
2.Conllection集合常用方法
| 方法 | 解釋 |
|---|---|
| boolean add(E e); | 向集合中添加元素 |
| boolean remove(E e) | 刪除集合中某個(gè)元素 |
| void clear() | 清空所有元元素 |
| boolean contains(E e) | 判斷集合中是否包含某個(gè)元素 |
| boolean isEmpty() | 判斷集合是否為空 |
| int size() | 獲取集合長(zhǎng)度 |
| Object [] toAarray() | 將集合轉(zhuǎn)成一個(gè)數(shù)組 |
代碼示例
public class test {
/*
*boolean add(E e); 向集合中添加元素
*boolean remove(E e) 刪除集合中某個(gè)元素
*void clear() 清空所有元元素
*boolean contains(E e) 判斷集合中是否包含某個(gè)元素
*boolean isEmpty() 判斷集合是否為空
*int size() 獲取集合長(zhǎng)度
*Object [] toAarray() 將集合轉(zhuǎn)成一個(gè)數(shù)組|
*/
public static void main(String[] args) {
Collection <String> coll =new ArrayList<>();
//boolean add(E e); 向集合中添加元素
coll.add("hello");
coll.add("world");
coll.add("Allen");
coll.add("java");
System.out.println(coll);
//boolean remove(E e) 刪除集合中某個(gè)元素
// boolean result = coll.remove("hello");
// System.out.println(result); //true
// System.out.println(coll); //[world, Allen, java]
// void clear() 清空所有元元素
// coll.clear();
// System.out.println(coll); //[]
// boolean contains(E e) 判斷集合中是否包含某個(gè)元素
// boolean result = coll.contains("java");
// System.out.println(result); //true
//boolean isEmpty() 判斷集合是否為空
System.out.println(coll.isEmpty()); //false
// int size() 獲取集合長(zhǎng)度
System.out.println(coll.size());
// Object [] toAarray()
Object[] arr = coll.toArray();
for (int i =0 ;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}