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