标题: HashSet的问题 [打印本页] 作者: 梵天的梦 时间: 2014-2-22 14:33 标题: HashSet的问题 package cn.itcast.day1;
import java.util.*;
public class ReflectTest2 {
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Collection collection = new HashSet(); ReflectPoint pt1 = new ReflectPoint(2,3); ReflectPoint pt2 = new ReflectPoint(3,3); ReflectPoint pt3 = new ReflectPoint(2,3); collection.add(pt1); collection.add(pt2); collection.add(pt3); pt1.y = 8; collection.remove(pt1); System.out.println(collection.size());//由于RelectPoint的成员变量y是参加hashCode计算的,所以在这里修改pt1.y的值后再执行remove集合的 size值还是2。remove(pt1),这里的pt1是修改前的还是修改后的? Iterator iterator=collection.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next());//结果:[2,8] [3,3] } }
}由于remove没有找到pt1进行删除,那么是不是在执行pt1.y=8这条语句之后collection对象自动调用什么方法又从新向集合中添加了一个new ReflectPoint(2,8)对象?---------package cn.itcast.day1;
/** * @author thinkpad * */public class ReflectPoint { private int x; public int y;
public ReflectPoint(int x, int y) { super(); 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 ReflectPoint other = (ReflectPoint) obj; if (x != other.x) return false; if (y != other.y) return false; return true; }}
作者: 戚兴海 时间: 2014-2-22 15:36
好乱的一坨,麻烦整理清楚了啊作者: 梵天的梦 时间: 2014-2-23 11:46
package cn.itcast.day1;
import java.util.*;
public class ReflectTest2 {
/** * @param args */
public static void main(String[] args) {
// TODO Auto-generated method stub
Collection collection = new HashSet();
ReflectPoint pt1 = new ReflectPoint(2,3);
ReflectPoint pt2 = new ReflectPoint(3,3);
ReflectPoint pt3 = new ReflectPoint(2,3);