上代码:
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,则将其移除。 请各位大侠结合这段话来解释两种重写方法的不同,小白谢过...

解决方案 »

  1.   

    //Object的String()
    public boolean equals(Object anObject)
    {}
    //Name的String()
    public boolean equals(Name n){} //参数类型不一致,不是方法重写(override)
    {}
      

  2.   

    大哥们,帮我看看这个代码 Student (String name,String school)
    {
    this(name,"beijing",school);
    }
    student继承person但是为什么这个构造方法没有考虑父类的构造方法那?一直不明白,本来以为编译应该出错的
      

  3.   

    构造方法中的第一句默认为:super();但你自己已经显式调用了this(..)的构造方法。所以就没有调用super()。构造方法里面只能选择调用一次super或者this方法,并且必须放在构造方法的第一行。
    上面的equals方法重写错了。类型必须是Object的。判断两个元素是否满足“==”首先调用hachCode()方法(看是否在同一个桶内),(如果在)然后调用equals()方法