public 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;
  }
 
}import java.util.*;public class Basecontainer {
public static void main(String[] args) {
Collection c = new HashSet();
c.add("hello");
c.add(new Name("ds","as"));
c.add(new Integer(123));
System.out.println(c.remove(new Integer(123)));
//c.remove(new Integer(123));
System.out.println(c.remove(new Name("ds","as")));
System.out.print(c);
}两个类
用容器添加object运行结果为
true
false
[ds as, hello]
为什么第一个是true第二个是false呢?

解决方案 »

  1.   

    因为你没有给Name类重写equals()和hashCode()方法。
      

  2.   

    Integer由于auto boxing unboxing机制被视作同一
    而Name却是两个不同的对象 
    解决办法可以通过操作同一引用或如1楼
      

  3.   

    Integer a = new Integer(123)
    Integer b = new Integer(123)
    Integer类实现的Object类的hashcode方法
    所以a和b生成的hashcode是一样的,存在HashSet中只是一个引用
    Name类没有实现hashcode方法
    Name a = new Name("ds","as")
    Name b = new Name("ds","as")
    a和b的hashcode是a和b的地址
    HashSet 中remove方法移除的对象,移除的时候也是根据hashcode操作的
    所以你的结果为true,false
      

  4.   


    import java.util.*; 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 n = (Name)obj;
      return n.firstName.equals(firstName) && n.lastName.equals(lastName);
      } else {
      return false;
      }
     }
     public int hashCode() {
      return firstName.hashCode();//有带改进,这样写不规范
     }
    } public class Basecontainer { 
    public static void main(String[] args) { 
    Collection c = new HashSet(); 
    c.add("hello"); 
    c.add(new Name("ds","as")); 
    c.add(new Integer(123)); 
    System.out.println(c.remove(new Integer(123))); 
    //c.remove(new Integer(123)); 
    System.out.println(c.remove(new Name("ds","as"))); 
    System.out.print(c); 
    } }