请看我修改的代码:- import java.util.*;
- class HashSetQue
- {
- public static void main(String[] args)
- {
-
- //ReflectPoint pt1 = new ReflectPoint(1,1);
- Collection collection = new HashSet();
- //这样才可以,你那样写代码,相等于是一个对象
- collection.add(new ReflectPoint(1,1));
- collection.add(new ReflectPoint(1,1));
- //collection.add(pt1);//这里又添加一次pt1没有成功。 //ReflectPiont类,里面重写了hashCode()和equals()方法
- System.out.println(collection);
-
- }
- }
- class ReflectPoint {
- public int x;
- public int y;
- public ReflectPoint(int x, int y) {
- super();
- this.x = x;
- this.y = y;
- }
-
- public int hashCode(){
- System.out.println("hashcode");
- return 1;
- }
- //这个equals()方法永远返回false,按理说同样的元素应该能再次添加的
- public boolean equals(Object obj){
- return false;
- }
- public String toString(){
- return "("+x+","+y+")";
- }
- }
复制代码 |