Java在HashSet中禁止新增重複物件
阿新 • • 發佈:2022-03-19
package com.set; public class Cat { private String name; private int month; private String species; //構造方法 public Cat(String name, int month, String species) { this.name = name; this.month = month; this.species = species; } //get和set方法 public String getName() {return name; } public void setName(String name) { this.name = name; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public String getSpecies() { return species; } public void setSpecies(String species) {this.species = species; } @Override public String toString() { return "Cat{" + "name='" + name + '\'' + ", month=" + month + ", species='" + species + '\'' + '}'; } }
package com.set; import java.util.HashSet;import java.util.Iterator; import java.util.Set; public class CatTest { public static void main(String[] args) { Cat huahua=new Cat("花花",12,"英國短毛貓"); Cat fanfan=new Cat("凡凡",3,"中華田園貓"); Set set=new HashSet(); set.add(huahua); set.add(fanfan); Iterator it= set.iterator(); while (it.hasNext()){ System.out.println(it.next()); } System.out.println("------------------------------"); Cat huahua01=new Cat("花花",12,"英國短毛貓"); set.add(huahua01); it=set.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } }
add方法會呼叫hashCode、equals方法進行判斷,此時未重寫hashCode和equals方法,由於預設每個物件的hashCode值都不一樣,重複的物件huahua01將會新增到集合中:
@Override public int hashCode() { final int prime=31; int result=1; result=prime*result+month; result=prime*result+((name==null)?0:name.hashCode()); result=prime*result+((species==null)?0:species.hashCode()); return result; } @Override public boolean equals(Object obj) { if(this==obj) return true; if(obj.getClass()==Cat.class){ Cat cat=(Cat) obj; return cat.getName().equals(name) && (cat.getMonth()==month) && (cat.getSpecies().equals(species)); } return false; }
在重寫hashCode和equals方法後,重複的物件不會被新增,執行結果為: