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下输出结果:
命令窗口下输出结果:
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下输出结果:
命令窗口下输出结果:
就是需要你自己去实现equals和hashCode方法
set集合才能判断加入的对象是否相同啊
默认从Object类继续而来的hashCode()通过内存地址来生成哈希值。