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;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值