Collection Framework 笔记
程序员文章站
2022-03-14 10:29:13
...
Java 2简化集合框架图
set集合众的对象唯一性的判断:
class ClientVO{
private int id;
private String name;
public ClientVO(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ClientVO) {
ClientVO vo = (ClientVO) obj;
if(this.getName()!=null && this.getName().equals(vo.getName())){
return true;
}
}
return false;
}
@Override
public int hashCode() {
return 32*id+id;
}
}
private static void testHashSet(){
HashSet set=new HashSet();
set.add(new ClientVO(111,"ChoeLea"));// add item 1
set.add(new ClientVO(111,"Joe")); // add item2 which has the same hashcode with item1
set.add(new ClientVO(123,"Joe")); // item 3
System.out.println(set.size()); //Result:3
set.add(new ClientVO(111,"Joe"));// item 4
System.out.println(set.size());//Result:3 so the items 4 can not be added into the set
System.out.println(set.contains(new ClientVO(11,"Joe")));//Result: false;
System.out.println(set.contains(new ClientVO(111,"Joe11")));//Result: false;
System.out.println(set.contains(new ClientVO(111,"Joe")));//Result: true;
}
HashSet 从hash这个关键字可以看出是无序的。 HashSet通过equals && hashCode 方法来判断是否重复。contain的判断也是同样的规则。HashSet是非线程安全。
LinkedHashSet 继承自HashSet,因此在判断是否重复上有同样的规则。
TreeSet是实现set接口有序的集合,所以所有加入TreeSet的对象需要实现Comparable 接口,否则将抛出异常: java.lang.ClassCastException