HashSet集合

轉載自     http://hi.baidu.com/shirdrn/item/a4bd2d3153bdfec32e8ec2a1


java.lang.Object
   |_ java.util.AbstractCollection<E>
        |_ java.util.AbstractSet<E>
              |_ java.util.HashSet<E>

HashSet中不允許有重複的元素。例如:

Set hashSet = new HashSet();
   hashSet.add(new String("aaa"));
   hashSet.add(new String("bbb"));
   hashSet.add(new String("ccc"));
   hashSet.add(new String("aaa"));
   hashSet.add(new String("aaa"));

通過hashSet.size()獲取它含有元素的個數,上面去掉重複的元素後,hashSet.size()=3。也就是說,在向HashSet中添加(add())元素的時候,對於重複的元素,只在HashSet中保留一個副本。

另外,HashSet中元素的順序是隨機的,包括添加(add())和輸出都是無序的。

對HashSet集合的一些常用操作:

add(Object)            :添加元素(Object);

addAll(Collection)      :向HashSet中添加一個集合(Collection);

remove(Object)         :***一個指定的元素(Object);

removeAll(Collection) :***一個指定的集合(Collection);

size()                           :HashSet的容量,即HashSet內元素的個數;

isEmpty()                   : 判斷HashSet是否爲空,即[]或size()=0,返回true或false;

contains(Object)         :判斷某個元素(Object)是否在HashSet中,返回true或false;

containsAll(Collection):判斷HashSet是否包含某個集合(Collection);

clear()                        :清空HashSet,使得size()=0;

toArray()                      :將HashSet轉換成一個Object[];

iterator()                     :構造一個HashSet迭代器,用於輸出HashSet中的元素

使用迭代器輸出HashSet中的元素,例如:

Iterator it = hashSet.iterator();
   while(it.hasNext()){
    System.out.println((String)it.next());

   }

假設有一個Person類:

class Person{
private String name;
private Integer age;
public Integer getAge() {
   return age;
}
public void setAge(Integer age) {
   this.age = age;
}
public String getName() {
   return name;
}
public void setName(String name) {
   this.name = name;
}

}

構造兩個Person的實例:

Person p1 = new Person();
   p1.setName("shirdrn");
   p1.setAge(new Integer(26));
   Person p2 = new Person();
   p2.setName("shirdrn");
   p2.setAge(new Integer(26));

加入到HashSet中:

Set hashSet = new HashSet();
   hashSet.add(p1);
   hashSet.add(p2);

按理說,加入的這兩個Person實例是相同的,HashSet應該只選擇一個添加到集合裏面。其實不然,此時的hashSet.size()=2。

這主要是由於Object擁有hashCode()和equals()兩個方法,它認爲具有相同的hashcode的對象纔是同一個對象,即對同一個對象的引用。


所以必須在對應的實體類中重寫hashCode()和equals()兩個方法。在Person類中重寫hashCode()和equals()兩個方法,如下所示:

public boolean equals(Object o){
   if(this == o){
    return true;
   }
   if(! (o instanceof Person)){
    return false;
   }
   final Person other = (Person)o;
   if(this.name.equals(other.getName()) && this.age.equals(other.getAge())){
    return true;
   }
   else{
    return false;
   }
}

public int hashCode(){
   int result;
   result = (name == null?0:name.hashCode());
   result = 37*result + (age == null?0:age.hashCode());
   return result;
}

這時,再進行上面的測試,發現hashSet.size()=1。此時,對象p1和p2具有相同的hashcode,HashSet認爲添加的兩個Person實例是同一個對象,只把一個添加到集合裏面。

這在Hibernate中非常關鍵。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章