import java.util.*;
public class BasicContainer {
public static void main(String args[]) {
Collection c = new HashSet();
Name n = new Name("ye","dame");
Name m = new Name("ye","dame");
c.add(n);
System.out.println(c.remove(m));
System.out.println(c);
}
}class Name{
String firstname;
String secondname;
Name(String firstname,String secondname) {
this.secondname = secondname;
this.firstname = firstname;
}
public boolean equals(Name n) {
return (this.secondname.equals(n.secondname)) && (this.firstname.equals(n.firstname));
}
public int hashCode() {
return firstname.hashCode();
}
}我明白我是重载了方法equals,不是重写,但是我传的参数是我重载的方法,在调用方法后其结果仍为false;
System.out.println(n==m); false
我是想对容器C 内的对象进行删除,当n equals m时候,对c 内的对象n移除,但运行结果是不能移除啊。什么原因。
Collection c = new HashSet();
Name n = new Name("ye","dame");
Name m = new Name("ye","dame");
c.add(n);
System.out.println(c.remove(n));
System.out.println(c);true
[]
avapublic boolean equals(Object o) {
if(n instanceof Name){
Name n = (Name)o;
return (this.secondname.equals(n.secondname)) && (this.firstname.equals(n.firstname));
}
return false;
}
[/code]