- Java code
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.equals(m)); true
System.out.println(n==m); false
------解决方案--------------------
调用前会被向上转换成Object,你重载的不可见
------解决方案--------------------
可以删除的,你add的是n,删除m当然不行了,改一下
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
[]
------解决方案--------------------
调用前会被向上转换成Object,你重载的不可见,所以不调用你写的,会调用Object的equals(Object)方法,而你没重写,remove当然找不到,结果当然不能移除...