容器:Java API所提供的一系列类的实例,用于在程序中存放对象。JDK所提供的容器类在java.util包中。 Collection接口定义了存取一组对象的方法,其子接口Set和List分别定义了存储方式。
Set中的数据对象没有顺序且不可重复。
List中的数据对象有顺序且可以重复。
Map接口定义了存储"键(key)-值(value)映射对"的方法
Collection接口中所定义的方法:
int size(); //多少元素
boolean isEmpty();//是否为空
void clear();//清空
boolean contains(Object element);//是否包含某个对象
boolean add(Object element);//添加元素
boolean remove(object element);//删除
Iterator iterator();
boolean containsAll(Collection c);//是不是包含另一个集合中所以的元素
boolean addAll(Collection c);//全部添加
boolean removeAll(Collection c);//全部删除
boolean retainAll(Collection c);//求交集
Object[] toArray();//转化成对象类数组
boolean isEmpty();//是否为空
void clear();//清空
boolean contains(Object element);//是否包含某个对象
boolean add(Object element);//添加元素
boolean remove(object element);//删除
Iterator iterator();
boolean containsAll(Collection c);//是不是包含另一个集合中所以的元素
boolean addAll(Collection c);//全部添加
boolean removeAll(Collection c);//全部删除
boolean retainAll(Collection c);//求交集
Object[] toArray();//转化成对象类数组
Collection里面装的都是对象,不能是基础数据类型。因为基础数据类型存放在栈中,随时可能收回。
remove()方法调用equals()方法,所以自己实现的类要重写equals方法和hashCode()方法。
import java.util.*;
public class TestCollection{
public static void main(String[] args){
Collection c = new ArrayList();
c.add("hello");
c.add(new Integer(100));
c.remove("hello");
System.out.println(c.size());
System.out.println(c);
}
}
public class TestCollection{
public static void main(String[] args){
Collection c = new ArrayList();
c.add("hello");
c.add(new Integer(100));
c.remove("hello");
System.out.println(c.size());
System.out.println(c);
}
}