输出结果为何有三个一样的Name对象
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下输出结果:
命令窗口下输出结果:
[解决办法]
三个对象都是 new的,是不同的对象!地址不同。如果你想对象里面的值相同就表示对象相同,你得重写equals方法和hashCode方法!
[解决办法]