java基础--HashSet

本文深入探讨了使用HashSet时可能导致内存泄漏的问题,特别是当对象的哈希值发生变化后,如何影响对象在HashSet中的存储及检索。通过一个具体示例,演示了如何避免此类问题的发生。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package Reflect.field;
/**内存泄漏
 * 当一个对象被存储进HashSet集合以后,就不能修改这个对象中的那些参与计算
 * 哈希值的字段了,否则,对象修改后的哈希值和最初存储进HashSet集合中时的哈希值
 * 就不同了,在这种情况下,即使在contains方法使用该对象的当前引用作为的参数去
 * HashSet集合中检索对象,也将返回不到对象的结果,这也会导致无法从HashSet集合
 * 中单独删除当前对象,从而造成内存泄漏。
 * @author xiaoyu
 *
 */
public class Point {

	int y;

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public Point(int y) {
		super();
		this.y = y;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 *
	 *对象存储于基于hash算法的集合中,该方法才有价值.
	 *
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + y;
		return result;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Point other = (Point) obj;
		if (y != other.y)
			return false;
		return true;
	}


	
}


package Reflect.ArrayList_HashSet;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;

import Reflect.field.Point;

public class RelectTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Point p1=new Point(1);
		Point p2=new Point(2);
		Point p3=new Point(3);
		Point p4=new Point(3);
		Collection<Point> collection=new HashSet<Point>();
		collection.add(p1);
		collection.add(p2);
		collection.add(p3);
		collection.add(p4);
		System.out.println(collection.size());//输出3;如果没有重写Point类的hashCode和equals方法,则输出4
	
		Collection<Point> collection2=new ArrayList<Point>();
		collection2.add(p1);
		collection2.add(p2);
		collection2.add(p3);
		collection2.add(p4);
		System.out.println(collection2.size());//4
		
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值