怎样才能避免,既能修改集合中的元素,又避免造成内存泄漏?
该怎么处理?
public class Demo {
public int x;
public int y;
public Demo(int x,int y){
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + x;
result = PRIME * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Demo other = (Demo) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
import java.util.*;
public class Test3 {
public static void main(String[] args) {
Collection collections = new HashSet();
Demo d1 = new Demo(3,3);
Demo d2 = new Demo(5,5);
Demo d3 = new Demo(3,3);
collections.add(d1);
collections.add(d2);
collections.add(d3);
collections.add(d1);
d1.y = 0;
collections.remove(d1);
System.out.println(collections.size());
}
} |
|