需要比较两个对象是否相等,需要重写equals方法,重写equals方法必重写hashcode方法.

参考资料:

 http://www.cnblogs.com/honoka/p/4827721.html 

下面是自己写

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方法一致.

比如说,我们忽略cat的属性year,即无论year是否相同,只要其它的属性相同,那么两个对象就相同,此时的equals方法就需要删除this.year == cat.getYear()的判断,hashcode方法里也需要将year参数删去.