我有一个Check Entity
我有三个属性的地方,包括 Id 并且正在使用 Id 作为哈希码,以便使用和检查重复项。
现在使用以下代码删除重复项
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;
}
}