Collection集合、add、remove、clear和遍歷元素部分
Collection是集合頂層接口,不能被實(shí)例化
(`Collection collection = new Collection();` 是錯(cuò)誤的)。但是可以以向上轉(zhuǎn)型方式實(shí)現(xiàn)創(chuàng)建。
```java
Collection collection = new ArrayList();
```
添加元素:
boolean add(object obj) 添加指定元素
```java
Collection collection = new ArrayList();
collection.add("luo")
String str = "羅"
collection.add(str)
System.out.println(collection)
/*結(jié)果為
luo
羅
*/
```
刪除元素:
1、boolean remove(object obj);移除指定元素
2、boolean clear(object obj);移除所有元素
```java
Collection collection = new ArrayList();
collection.add("luo")
String str = "羅"
collection.add(str)
System.out.println("--------")
collection.remove("luo")
System.out.println(collection)
System.out.println("--------")
collection.clear();
System.out.println(collection,size())
/*結(jié)果為
luo
羅
--------
羅
--------
0
*/
```
遍歷元素:1、用for用
2、迭代器:hasNext()有沒有下一個(gè)元素、next()要下一個(gè)元素、remove()刪除這個(gè)元素
```java
Collection collection = new ArrayList();
collection.add("luo")
String str = "羅"
collection.add(str)
for (Object object:collection){
System.out.println(object);
}
/*
結(jié)果為
luo
羅
*/
```
```java
Collection collection = new ArrayList();
collection.add("luo")
String str = "羅"
collection.add(str)
Iterator iterator = collection.iterator();
while (iterator.hasNext()){
String a = (String) iterator.next();
System.out.println(a);//在用迭代器時(shí)是不允許用collection.remove進(jìn)行移除!!
//可以用迭代器里的remove進(jìn)行移除!!
}
```
浙公網(wǎng)安備 33010602011771號(hào)