嗨,我是java的新手,因为我知道set collection不会重复,当contains已经存在于collection中时,它的contains方法应该返回true.我试图在程序下运行,但我得到了意想不到的结果.
public class UserDefinedName {
private final String first, last;
public UserDefinedName(String first, String last) {
this.first = first;
this.last = last;
}
public boolean equals(Object o) {
if (!(o instanceof UserDefinedName))
return false;
UserDefinedName n = (UserDefinedName) o;
return n.first.equals(first) && n.last.equals(last);
}
public static void main(String[] args) {
Set<UserDefinedName> s = new HashSet<UserDefinedName>();
s.add(new UserDefinedName("Carballo", "Videl"));
System.out.println(s.contains(new UserDefinedName("Carballo", "Videl")));
}
}
Run Code Online (Sandbox Code Playgroud)
我期待输出为true但程序打印为false.我做错了什么?