一、集合框架基本概念
集合是長度可變的用於存取數據的容器,可以存儲不同類型的對象,存儲的都是對象的引用(地址)。
二、集合框架基本分類
1、集合框架圖解
2、基本分類
三、JAVA包裝類
1、基本數據類型對應的包裝類
int:Integer
byte: Byte
short:Short
long:Long
float:Float
double:Double
char:Character
boolean:Boolean
四、Collection接口
1、Collection接口基本概念
Collection接口定義了存取一組對象的方法,其子接口Set和List分別定義了存儲方式。
2、Collection主要方法摘要
boolean add();
添加元素到 collectionvoid clear();
移除此 collection 中的所有元素boolean contains();
如果此 collection 包含指定的元素,則返回 trueboolean equals();
比較此 collection 與指定對象是否相等int hashCode();
返回此 collection 的哈希碼值boolean isEmpty();
判斷此 collection 是否爲空Iterator<object> iterator();
返回在此 collection 的元素上進行迭代的迭代器boolean remove();
從此 collection 中移除指定元素的單個實例,如果存在的話int size();
返回此 collection 中的元素數Object[] toArray();
返回包含此 collection 中所有元素的數組
舉例說明某些方法
public class CollectionDemo{
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("hello");
c.add(1);
c.add('a');
c.add(new Integer(100));
System.out.println("是否成功移除'a':" + c.remove('a'));
System.out.println("集合是否爲空:" + c.isEmpty());
System.out.println("集合是否包含'helllo':" + c.contains("hello"));
System.out.println("集合數據有:" + c);
System.out.println("集合長度 = " + c.size());
//將集合轉成String類型的數組並輸出
Object[] array = c.toArray();
System.out.print("數組裏面的元素有:");
for(Object i: array) {
System.out.print(i + " ");
}
c.clear(); //清空集合
System.out.println("\n集合中是否還有元素:" + c);
}
}
得到如下結果:
是否成功移除'a':true
集合是否爲空:false
集合是否包含'helllo':true
集合數據有:[hello, 1, 100]
集合長度 = 3
數組裏面的元素有:hello 1 100
集合中是否還有元素:[]
五、Iterator接口
1、基本概念
在上面示例中,利用System.out.println("集合數據有:" + c);
直接打印集合c
相當於調用了toString()
方法。除了這種方式外,Collection有其特有的輸出方式:迭代器Iterator。
//獲取迭代器
Iterator it = c.iterator();
System.out.println("利用迭代器iterator輸出結果爲:");
while(it.hasNext()) {
System.out.print(it.next() + " ");
}
//輸出結果爲
利用迭代器iterator輸出結果爲:hello 1 100
另外,也可以用for循環輸出
System.out.print("利用迭代器iterator輸出結果爲:");
for(Iterator it = c.iterator(); it.hasNext(); ) {
System.out.print(it.next() + " ");
}
//輸出結果同樣爲
利用迭代器iterator輸出結果爲:hello 1 100
所有實現了Collection接口的集合類都有一個Iterator方法,用於返回一個實現了Iterator接口的對象,Iterator對象稱作迭代器,用以方便的實現對集合內元素的遍歷操作。
2、Iterator主要方法摘要
boolean hasNext();
//判斷遊標右邊是否還有元素Object next();
//返回遊標右邊的元素並將遊標移動到下一個位置void remove();
//刪除遊標左面的元素,在執行完next()方法之後該操作只能執行一次