//当你覆写equals 方法时,一定要记着覆写hashCode 方法。 //否则类与基于hashCode的集合类一起正确使用时,会出现不可预期的行为。 //为了避免在覆盖override时错误的进行了重载overload,应该始终在覆盖的方法前加上@Override。 Set<Name> s = new HashSet<Name>(); s.add(new Name("Mickey", "Mouse")); System.out.println(s.contains(new Name("Mickey", "Mouse"))); //false class Name { protected String first, last; public Name(String first, String last) { this.first = first; this.last = last; } @Override public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return n.first.equals(first) && n.last.equals(last); } /* @Override public int hashCode() { return 37 * first.hashCode() + last.hashCode(); }*/ }
覆写equals 方法时,一定要记着覆写hashCode 方法。
猜你喜欢
转载自jaesonchen.iteye.com/blog/2297866
今日推荐
周排行