code:
import java.util.*;class Name {
@SuppressWarnings("unused")
private String firstName, lastName;
Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}public class TestSet {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Set s = new HashSet();
s.add(new Name("f1", "f2"));
s.add(new Integer(100));
s.add("Hello");
s.add(new Name("f1", "f2"));   //相同元素不会被加入
s.add(new Name("f1", "f2"));   //相同元素不会被加入
s.add(new Integer(100));   //相同元素不会被加入
s.add("Hello");   //相同元素不会被加入

System.out.println(s);
}
}
eclipse下输出结果:
命令窗口下输出结果:

解决方案 »

  1.   

    三个对象都是 new的,是不同的对象!地址不同。如果你想对象里面的值相同就表示对象相同,你得重写equals方法和hashCode方法!
      

  2.   


    就是需要你自己去实现equals和hashCode方法
    set集合才能判断加入的对象是否相同啊
      

  3.   

    自己写的类如果需要比较是否相等,或是要在使用HashMap和HashSet等类时用到,应该重写equals()和hashCode()方法,否则可能出现问题。
    默认从Object类继续而来的hashCode()通过内存地址来生成哈希值。