`
zds420
  • 浏览: 198406 次
  • 性别: Icon_minigender_1
  • 来自: 合肥
社区版块
存档分类
最新评论

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

    博客分类:
  • J2SE
 
阅读更多

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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics