容器类自定义类型进行比较的时候务必重写equals方法务必要重写hashCode方法
package com.study;
import java.util.*;
public class OverrideEquaslCode {
public static void main(String []args) {
Collection c2= new HashSet();
c2.add("Colleciton Hello1");
c2.add("Colleciton Hello2");
c2.add("Colleciton Hello3");
c2.add(new ComputerClass("Computer1","100,200"));
c2.add(new ComputerClass("Computer2","200,300"));
System.out.println(c2);
c2.remove("Colleciton Hello3");
System.out.println(c2); // 可以删除,基础类型继承了Object基类的equals()方法
//下面的输出为false,因为没有自定义类型需要重写equals()方法和hashCode()方法且hashCode()比较键值对.
System.out.println(c2.remove(new ComputerClass("Computer1","100,200"))); //重写equals方法务必要重写hashCode方法
System.out.println(c2);
}
}
class ComputerClass {
private String brand_name;
private String properties;
public ComputerClass(String brand_name,String properties) {
this.brand_name=brand_name;
this.properties=properties;
}
public boolean equals(Object obj) {
ComputerClass cClass = (ComputerClass)obj;//强制类型转换
if(obj instanceof ComputerClass) { //instaceof 比较左边对象是否是它右边的类的实例
return brand_name.equals(cClass.brand_name) && properties.equals(cClass.properties);
}
else {
return super.equals(obj); //否则交给父类进行比较
}
}
public int hashCode() {
return brand_name.hashCode();
}
public String getBrand_name() {
return brand_name;
}
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
public String getProperties() {
return properties;
}
public void setProperties(String properties) {
this.properties = properties;
}
}