1. The characteristics of the collection :
- Provide a storage model with variable storage space, and the stored data capacity can be changed at any time
- The collection stores a reference type, so the packaging class should be used when storing, for example, Integer should be used to store int
2. Collection classification :
3. Create a Collection collection object :
Because Collection is an interface, objects should be created in a polymorphic manner
Collection<String> c=new ArrayList<String>();
Example:
package Collection;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
public class CollectionDemo01 {
public static void main(String[] args) {
//创建Collection集合的对象
Collection<String> c=new ArrayList<String>();
//添加元素 boolean add(E e)
c.add("hello");
c.add("world");
c.add("java");
//ArrayList重写了toString方法
System.out.println(c);
}
}
4. Collection commonly used methods:
boolean add(E e) 添加元素
boolean remove(Object o) 从集合中移除指定元素
void clear() 清空集合中的元素
boolean contains(Object o) 判断集合中是否存在指定元素
boolean isEmpty() 判断集合是否为空
int size() 集合的长度,也就是集合中元素的个数
Example:
package Collection;
import java.util.ArrayList;
import java.util.Collection;
public class CollectionDemo02 {
public static void main(String[] args) {
//创建Collection集合的对象
Collection<String> c=new ArrayList<String>();
//add永远返回true
System.out.println(c.add("hello"));
System.out.println(c.add("hello"));
System.out.println(c.add("world"));
System.out.println(c.remove("wold"));
System.out.println(c);
}
}
5. Iterator: collection-specific traversal method
- Iterator iterator returns the iterator of the elements in the collection, obtained by the iterator() method of the collection
- boolean hasNext(): returns true if the iterator has more elements
- E next(): returns the next element in the iterator
Example:
package Collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDemo03 {
public static void main(String[] args) {
//创建Collection集合的对象
Collection<String> c=new ArrayList<String>();
//add永远返回true
c.add("hello");
c.add("world");
c.add("java");
Iterator<String> it=c.iterator();
while(it.hasNext()){
//如果迭代器具有更多元素,返回
//System.out.println(it.next());
String s=it.next();//返回迭代器下一个元素
System.out.println(s);
}
}
}