HashSetTest.java
package com.collection;
import java.util.HashSet;
public class HashSetTest {
public static void main(String[] args) {
//此处容量会自动增到到2的倍数,增到4
HashSet<String> set = new HashSet<String>(3);
set.add("a");
set.add("b");
set.add("c");
set.add("d");
set.add("e");//这个时候set底层会创建一个长度为8的数组
//原来长度为4的数组会编程垃圾,等待回收
System.out.println(set);
}
}
HashSetTest2.java
package com.collection;
import java.util.HashSet;
class A{
private int count;
public A(int count){
this.count = count;
}
public boolean equals(Object obj){
if(this == obj)
return true;
if((obj != null) && (obj.getClass() == A.class)){
A targetobj = (A)obj;
//如果两个对象的关键属性相同
if(this.count == targetobj.count)
return true;
}
return false;
}
//当我们要把元素存入哈希表(HashSet/HashMap)时,
//此时应该重写hashCode方法
//hashCode不要写成了HashCode
public int hashCode(){
return 20;
}
}
public class HashSetTest2 {
public static void main(String[] args) {
HashSet<A> set = new HashSet<A>();
set.add(new A(2));
set.add(new A(2));
System.out.println(set);
}
}
HashSet存储顺序跟添加顺序不一致。