日期:2014-05-20  浏览次数:20818 次

不同equals方法的重写,对于集合类中删除操作的影响,跪求解释..
上代码:
import java.util.*;

public class BasicContainer1 {
  public static void main(String[] args) {
  Collection<Name> c = new HashSet<Name>();
//Name n1 = new Name("f1","l1");
//Name n2 = new Name("f2","l2");
//c.add(n1);
//c.add(n2);
c.add(new Name("f3","l3"));
System.out.println(c);
  //System.out.println(c.remove(new Name("f1","l1")));
//System.out.println(c.remove(n1));
  // System.out.println(c);
System.out.println(new Name("f1","l1")==null);
System.out.println(new Name("f1","l1").equals(new Name("f1","f2")));
System.out.println(c.remove(new Name("f3","l3")));
System.out.println(c);
  }
}

class Name{
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 name) {
if(name instanceof Name){
Name n = (Name)name;
if(this.firstName.equals(n.firstName) 
  && (this.lastName.equals(n.lastName))){
return true;
}
}

return false;

}*/

public boolean equals(Name n) {
if(firstName.equals(n.firstName) && lastName.equals(n.lastName)){
return true; 
}
return false;


public int hashCode() {
return firstName.hashCode();

}

}

以上两种equals方法有何不同?为什么采用第一种重写方法,可以删除HashSet中的元素,而第二种不行?我查看了API中HashSet的remove方法,但是不太理解,求各位大侠指点..public boolean remove(Object o) 如果指定元素存在于此 set 中,则将其移除。更确切地讲,如果此 set 包含一个满足 (o==null ? e==null : o.equals(e)) 的元素 e,则将其移除。 请各位大侠结合这段话来解释两种重写方法的不同,小白谢过...

------解决方案--------------------

Java code

//Object的String()
public boolean equals(Object anObject)
{}