import java.util.*;
public class BasicContainer
{
public static void main(String args[])
{
Collection c=new HashSet();
c.add("hello");
c.add(new Name("fi","li"));
c.add(new Integer(100));
System.out.println(c);c.remove("hello");
c.remove(new Integer(100));
System.out.println(c.remove(new Name("fi","li")));
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  obj)
{
if(obj instanceof Name)
{
Name name=(Name) obj;
return (firstName.equals(name.firstName))&&(lastName.equals(name.lastName));
  }
  return super.equals(obj);
}
public int hashCode()
{
return firstName.hashCode();
}*/
}

 请问注释掉的一部分是怎么被调用的,因为在程序中找不到对他们的引用(调用)然而注释掉以前跟注释掉以后却不一样呢?
谢谢!

解决方案 »

  1.   

    Set是无不重复的  怎样保持不重复??你是机器的话 你会怎么做??
      

  2.   

    Set是不重复的 如果你不重写equals()方法,它会调用父类equals()方法
    重写之后,他会调用你重写后的方法
      

  3.   

    又是hashcode的问题。不是没有引用,你用到HashSet的时候就用到了对象的hashcode值。HashSet存储的方式是散列的方式,根据hash码来存储。当比较HshSet中的元素是否为同一个是用元素对象的equals方法。
      lz注释的部分是重写了Object的equals和hashcode方法。当然对于hash存储的结构就会有作用。
      

  4.   

    你复写了equals方法,不加注释时就会用你的equals,加了注释就用object类自带的equals了 所以不一样吧