須要比較兩個對象是否相等,須要重寫equals方法,重寫equals方法必重寫hashcode方法.html
參考資料:java
http://www.cnblogs.com/honoka/p/4827721.html ide
下面是本身寫this
public class Cat { private String name; private String color; private String weight; private String high; private int year; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public String getWeight() { return weight; } public void setWeight(String weight) { this.weight = weight; } public String getHigh() { return high; } public void setHigh(String high) { this.high = high; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { // TODO Auto-generated method stub if(this == obj) { return true; } if(null == obj) { return false; } if(this.getClass() != obj.getClass()) { return false; } Cat cat = (Cat)obj; if ( this.name.equals(cat.getName()) && this.color.equals(cat.getColor()) && this.weight.equals(cat.getWeight()) && this.high.equals(cat.getHigh()) && this.year == cat.getYear() ) { return true; } return super.equals(obj); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { // TODO Auto-generated method stub return Objects.hash(this.name,this.color,this.weight,this.high,this.year); } }
equals方法須要與hashcode方法一致.code
好比說,咱們忽略cat的屬性year,即不管year是否相同,只要其它的屬性相同,那麼兩個對象就相同,此時的equals方法就須要刪除this.year == cat.getYear()的判斷,hashcode方法裏也須要將year參數刪去.htm