本帖最后由 ll6887691 于 2011-09-09 02:00:47 编辑

解决方案 »

  1.   

    谁说一定要覆盖equals()和hashCode()方法呀,你完全有权利不重写它,因为它可以调用父类的方法哦set可以保证对象的唯一性,由equals()方法确定,
    hash是保证快速查找,对象在堆中的存储位置由hashCode确定所以HashSet必定会调用它们,下面我强制让每个对象调用equals()和hashCode()返回的值是一样的,系统会认为每个对象都是同一个对象,你看看结果是不是只能添加一个Name对象
    import java.util.*;public class cc {
        public static void main(String[] args) {
    Collection c = new HashSet();

    c.add(new Name("f1", "l1"));
    c.add(new Name("f2", "l2"));
    c.add(new Name("f3", "l3"));

    Iterator i = c.iterator();

    while (i.hasNext()) {
        Name n = (Name) i.next();
        System.out.print(n.getFirstName() + " ");
    }
        }
    }// 然后 Name类 如下
    class Name {
        private String firstName, lastName ;
           public Name(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
        }    public String getFirstName() {
    return firstName;
        }    public String getLastName() {
    return lastName;
        }    public String toString() {
    return firstName + " " + lastName;
        }    // 这里需要不需要重写 equels 和 hasCode呢
        // 为什么
        
        public boolean equals(Object obj) {
    /*
     
     if (obj instanceof Name) {
        Name name = (Name) obj;
        return (firstName.equals(name.firstName))
        && (lastName.equals(name.lastName));
    }
    return super.equals(obj);
    */
    return true;//此时每个对象都返回true,因为我认为每个对象都是一样的,所以必须让hashSet看来每个对象也是一样的
        }    
        public int hashCode() {
    //return firstName.hashCode();
    return 1;//此时让Name对象都放在一起
    //对于良好的编程风格而言,你应该在重写equals()方法时,总是同时重写hashCode()方法
        }
    }//output:
     // f1 
    所以,要想确保你心目中的对象唯一性,你得重写它们