可能重复:
Removing duplicates from the list with different ways研究去除重复的元素
我是做了研究,并找到这下面的方法来从list..but删除重复的请指教是还有其他的方法,因为我正在研究这个问题,我想在集合中探索其他方法,这将是一个很好的例子。我对我的研究更感兴趣的是新的jdk 1.5有一些新东西提供这个背景
class Emp //implements Comparable
{
String name,job;
int salary;
public Emp(String n,String j,int sal)
{
name=n;
job=j;
salary=sal;
}
public void display()
{
System.out.println(name+"\t"+job+"\t"+salary);
}
public boolean equals(Object o)
{
Emp p=(Emp)o;
return this.name.equals(p.name)&&this.job.equals(p.job) &&this.salary==p.salary;
}
public int hashCode()
{
return name.hashCode()+job.hashCode()+salary;
}
/* public int compareTo(Object o)
{
Emp e=(Emp)o;
return this.name.compareTo(e.name);
//return this.job.compareTo(e.job);
// return this.salary-e.salary;
}*/
}
和最后一类将...
class EmpListDemo
{
public static void main(String arg[])
{
List list=new ArrayList();
list.add(new Emp("Ram","Trainer",34000));
list.add(new Emp("Sachin","Programmer",24000));
list.add(new Emp("Ram","Trainer",34000));
list.add(new Emp("Priyanka","Manager",54000));
list.add(1,new Emp("Ravi","Administrator",44000));
list.add(new Emp("Anupam","Programmer",34000));
list.add(new Emp("Priyanka","Manager",54000));
list.add(new Emp("Sachin","Team Leader",54000));
System.out.println("There are "+list.size()+" elements in the list.");
System.out.println("Content of list are : ");
ListIterator itr1=list.listIterator();
while(itr1.hasNext())
{
Emp e=(Emp)itr1.next();
e.display();
}
//Removing duplicates from the list
Set hs = new HashSet();
hs.addAll(list);
list.clear();
list.addAll(hs);
System.out.println("******************************");
System.out.println("There are "+hs.size()+" elements in the set.");
System.out.println("Contents after modification : ");
Iterator itr=list.iterator();
while(itr.hasNext())
{
Emp e=(Emp)itr.next();
e.display();
}
}
}
如果你的容器需要没有重复,为什么你'List'而不是'HashSet'?您需要使用最适合您需求的数据结构。 – Vlad 2012-08-01 17:20:26