你这要重写equals方法 。现在默认的是比较地址,你要写成比较内容的。

解决方案 »

  1.   

    list加了P3没加P3肯定是不行的了,重写equals方法比较内容没试过,两个指向的地址肯定是不一样的
      

  2.   

    if (list.contains(p1)) 这个是查找对像的地址吗? 不是整个对象的查找?
      

  3.   

    new出来的对象,都会重新分配一个地址的。p3和p1,是2个不同的对象,但是他们的内容是一样的。
      

  4.   

    请参考下面做法:
    应用环境:从数据库中查询出满足一系列条件的记录,然后以对象的形式封装到List中去。此时假设有两个条件A和B,满足A的记录集和为ListA,满足B的记录集合为ListB,现在要将ListA和ListB合并为一个List,注意ListA和ListB中可能有重复的记录(因为可能某条记录即满足条件A又满足条件B),要过滤掉重复的记录。 
    方法过程:我们假设List中存放的对象都是Order对象,属性orderId用于标识一个唯一的Order对象。 
              List<order> list = new ArrayList<Order>(); 
              if(ListA!=null){ 
                Iterator it= ListA.iterator(); 
                while(it.hasNext()){ 
                    list.add((Order)it.next()); 
                } 
             } 
    if(ListB!=null){ 
                Iterator it= ListB.iterator(); 
                while(it.hasNext()){ 
                  Order o=(Order)it.next(); 
                  if(!list.contains(o)) 
                      list.add(o); 
                } 
             } 
              首先我们将ListA中的对象全部装入到list中,然后在装入ListB中对象的 
              时候对ListB中的每个元素进行一下判断,看list中是否已存在该元素,这里我们使用List接口的contains()方法。它的原理是这样的:如上例中的 
              list.contains(o),系统会对list中的每个元素e调用o.equals(e),方法,加入list中有n个元素,那么会调用n次o.equals(e),只要有一次o.equals(e)返回了true,那么list.contains(o)返回true,否则返回false。因此为了很好的使用contains()方法,我们需要重新定义下Order类的equals方法,根据我们的业务逻辑,如果两个Order对象的orderId相同,那么我们认为它们代表同一条记录,于是equals方法定义如下: 
              public boolean equals(Object obj) { 
                 if (this == obj) 
                     return true; 
                 if (obj == null) 
                     return false; 
                 if (getClass() != obj.getClass()) 
                     return false; 
                 final Order other = (Order) obj; 
                  if(this.getOrderid()!=other.getOrderid()) 
                     return false; 
                 return true; 
            } 
              这样只要ListB中有一条记录的orderId和list中的某条记录的orderId 
    相等,那么我们就认为该记录已存在,不再将它放入list,这样就避免了重复记录的存在。
      

  5.   


    public class Privilege { private String id;
    private String name;
    public String getId() {
    return id;
    }
    public void setId(String id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
     public boolean equals(Object obj) { 
             if (this == obj) 
                 return true; 
             if (obj == null) 
                 return false; 
             if (getClass() != obj.getClass()) 
                 return false; 
             final Privilege other = (Privilege) obj; 
              if(this.getId()!=other.getId()) 
                 return false; 
             return true; 
        } 


    }
    改一下这个实体就可以了