j2sdk所提供的容器API位于java.util包内。
容器API的类图结构如下图所示:
Collection接口一定义了存取一组对象的方法,其子接口Set和List分别定义了存储方式。
Set中的数据对象没有存取顺序且不可以重复。(通过equals来判断)
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();
Collection 方法举例
import java.util.*;
public class Test {
public static void main(String[] args) {
Collection c = new HashSet();
c.add("hello");
c.add(new Name("f1","11"));
c.add(new Integer(100));
c.remove("hello");
c.remove(new Integer(100));
System.out.println(c.remove(new Name("f1","11")));
System.out.println(c);
}
}
class Name {
private String firstName,secondName;
public Name(String firstName,String secondName) {
this.firstName = firstName;
this.secondName = secondName;
}
public String getfirstName() {return firstName;}
public String getsecondName() {return secondName;}
public String toString() {
return firstName+" "+secondName;
}
}
两个对象如果内容一样,Hashcode也必须一样
容器类对象在调用remove、contains等方法时需要比较对象是否相等,这会涉及到对象类型的equals 方法和hashCode方法:对于自定义的类型,需要要重写equals和hashCode方法以实现自定义的对象相等规则。●注意:相等的对象应该具有相等的hash codes。增加Name类的equals和hashCode方法如下:
public boolean equals(Object obj) {
if(obj instanceof Name) {
Name name = (Name) obj;//强制转换
return (firstName.equals(name.firstName))&&(secondName.equals(name.secondName));
}
return super.equals(obj);
}
public int hashCode() {
return firstName.hashCode();
}