首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Collection之容器类的自定义对象的比较亟需重写equals和hashCode

2012-10-31 
Collection之容器类的自定义对象的比较需要重写equals和hashCode容器类自定义类型进行比较的时候务必重写e

Collection之容器类的自定义对象的比较需要重写equals和hashCode

容器类自定义类型进行比较的时候务必重写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;}}

?

热点排行