import java.util.*; 
public class SetTest3 

   public static void main(String[] args) 
    { 
                 HashSet hs=new HashSet(); 
                 hs.add(new Student(1,"zhangsan")); 
                 hs.add(new Student(2,"lisi")); 
                 hs.add(new Student(3,"wangwu")); 
                 hs.add(new Student(1,"zhangsan")); 
  
                 Iterator it=hs.iterator(); 
                 while(it.hasNext()) 
                 { 
                        System.out.println(it.next()); 
                 } 
     } 

class Student 

int num; 
String name; 
Student(int num,String name) 

           this.num=num; 
           this.name=name; 

public int hashCode() 

           return num*name.hashCode(); 

public boolean equals(Object o) 

           Student s=(Student)o; 
           return num==s.num && name.equals(s.name); 

public String toString() 

           return num+":"+name; 

} public int hashCode() 

           return num*name.hashCode();   //name的hashcode方法是什么

public boolean equals(Object o) 

           Student s=(Student)o; 
           return num==s.num && name.equals(s.name); //name的equals方法又是什么

解决方案 »

  1.   

    name String型的,Hashcode 源码:public int hashCode() {
    int h = hash;
    if (h == 0) {
        int off = offset;
        char val[] = value;
        int len = count;            for (int i = 0; i < len; i++) {
                    h = 31*h + val[off++];
                }
                hash = h;
            }
            return h;
        }equals:
        public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
    char v1[] = value;
    char v2[] = anotherString.value;
    int i = offset;
    int j = anotherString.offset;
    while (n-- != 0) {
        if (v1[i++] != v2[j++])
    return false;
    }
    return true;
        }
    }
    return false;
        }
      

  2.   

    name就一String 类型的,所以就是String 的hashCode和equals方法
      

  3.   

    如果没有这两个方法,则默认继承Object的这两个方法,两次:new Student(1,"zhangsan");程序认为产生了两个不同的对象。因为两次创建对象的hashCode不相等,HashSet容器认为是两个不同的对象。就都放到容器里了。
    楼主可以注释掉看看结果。