import java.util.*;
public class BasicContainer {
public static void main(String[] args) {
Collection c = new HashSet();
c.add("hello");
c.add(new Name("f1","l1"));
c.add(new Integer(100));
c.remove("hello");
c.remove(new Integer(100));
System.out.println
(c.remove(new Name("f1","l1"))); //如果我下面没重写Object的equals方法为什么不能修改Name的值??
System.out.println(c);
}
}
class Name /*implements Comparable*/ {
private String firstName,lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String toString() {
return firstName + " " + lastName;
}
public boolean equals(Object obj) {
if (obj instanceof Name) {
Name name = (Name) obj;
return (firstName.equals(name.firstName))
&& (lastName.equals(name.lastName));
}
return super.equals(obj);
}
public int hashCode() {
return firstName.hashCode();
}
}
public boolean equals(Object obj) {
这里传进来的是哪个Name ?
c.add(new Name("f1","l1")); 这个 ? 还是
System.out.println
(c.remove(new Name("f1","l1"))); 这个 ?
基础不是很好
public boolean equals(Object obj) {
这里传进来的是哪个Name ?
c.add(new Name("f1","l1")); 这个 ? 还是
System.out.println
(c.remove(new Name("f1","l1"))); 这个 ?
基础不是很好
当然是调用remove方法时的了,因为你要移除c.add(new Name("f1","l1")) 这个生成的Name。所以你要调用equal比较再生成一个Name比较两个内容是否相同:c.remove(new Name("f1","l1"))); (这里的new Name是新生成的)
public boolean equals(Object obj) {
这里传进来的是哪个Name ?
c.add(new Name("f1","l1")); 这个 ? 还是
System.out.println
(c.remove(new Name("f1","l1"))); 这个 ?
基础不是很好
后面那个,在打印对象时默认调用equals方法