可能重複:
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