我有一個Check Entity
我有三個屬性,包括Id和我使用Id作爲散列碼以便使用和檢查重複項。如何從arraylist中刪除重複項(舊對象)
現在重複越來越使用下面的代碼
Set<Check> unique = new LinkedHashSet<Check>(l);
List<Check> finalLst= new java.util.ArrayList<Check>();
finalLst.addAll(unique);
在輸出
這三個都來爲結果移除(C1,C2和C3),但我想(C4,C5和C6)。
Check c1 = new Check(1,"one");
Check c2 = new Check(2,"two");
Check c3 = new Check(3,"three");
Check c4 = new Check(1,"one");
Check c5 = new Check(2,"two");
Check c6 = new Check(3,"three");
輸出我得到現在:
id :1 ::2013-04-30 10:42:34.311
id :2 ::2013-04-30 10:42:34.344
id :3 ::2013-04-30 10:42:34.344
id :1 ::2013-04-30 10:42:34.344
id :2 ::2013-04-30 10:42:34.345
id :3 ::2013-04-30 10:42:34.345
1 :: 2013-04-30 10:42:34.311
2 :: 2013-04-30 10:42:34.344
3 :: 2013-04-30 10:42:34.344
輸出很期待:
id :1 ::2013-04-30 10:42:34.311
id :2 ::2013-04-30 10:42:34.344
id :3 ::2013-04-30 10:42:34.344
id :1 ::2013-04-30 10:42:34.344
id :2 ::2013-04-30 10:42:34.345
id :3 ::2013-04-30 10:42:34.345
1 :: 2013-04-30 10:42:34.344
2 :: 2013-04-30 10:42:34.345
3 :: 2013-04-30 10:42:34.345
我整個的代碼放在這裏:
package test.collection;
import java.text.SimpleDateFormat;
import java.util.*;
public class RemoveDuplicateInArrayList
{
public static void main(String args[])
{
Check c1 = new Check(1,"one");
Check c2 = new Check(2,"two");
Check c3 = new Check(3,"three");
Check c4 = new Check(1,"one");
Check c5 = new Check(2,"two");
Check c6 = new Check(3,"three");
List<Check> l = new java.util.ArrayList<Check>();
l.add(c1);
l.add(c2);
l.add(c3);
l.add(c4);
l.add(c5);
l.add(c6);
List<Check> finalLst= removeDuplicates(l);
Iterator<Check> iter = finalLst.iterator();
while(iter.hasNext())
{
Check temp = iter.next();
System.out.println(temp.getId()+" :: "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(temp.getCreationTme()));
}
}
public static List<Check> removeDuplicates(List<Check> l)
{
Set<Check> unique = new LinkedHashSet<Check>(l);
List<Check> finalLst= new java.util.ArrayList<Check>();
finalLst.addAll(unique);
return finalLst;
}
}
class Check
{
public Check(int id,String name)
{
this.id = id;
this.name = name;
this.creationTme = new Date();
System.out.println("id :"+this.id+" ::"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S").format(this.getCreationTme()));
}
private int id;
private String name;
private Date creationTme;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreationTme() {
return creationTme;
}
public void setCreationTme(Date creationTme) {
this.creationTme = creationTme;
}
@Override
public int hashCode()
{
return this.id;
}
@Override
public boolean equals(Object obj)
{
if(obj instanceof Check && ((Check)obj).id == this.id)
return true;
else return false;
}
}
下的選民,如果你有意識做出評論!!!!!!!!! – sunleo 2013-04-30 05:24:45
謝謝你所有的答案............ – sunleo 2013-04-30 07:01:45