黑马程序员技术交流社区
标题:
关于List集合的去重复元素的几点注意
[打印本页]
作者:
向日葵的曙光
时间:
2014-4-15 16:06
标题:
关于List集合的去重复元素的几点注意
对于List集合去重的问题,通过学习与测试,总结出以下几点
1.在进行删除重复元素时,如果删除的是一个对象,则必须重写equals方法,并且对
要删除的元素与Object类进行比较,如果是Object子类实例则必须将Object强制转换成新创建的类
2.在与此同时,必须定义一个新的集合容器,用来放与原来集合不相同的元素,然后返回这个新集合
3.
值得注意
,前两条是List集合去重都必须操作的。以前一直以为只有ArrayList集合才是这样处理,但经过试验后Vector、LinkedList集合去重用同样的方法处理。
以下是具体的代码实现:
package com.cg.test;
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList arrayList=new ArrayList();
arrayList=showArrayList(arrayList);
ArrayList arrayList1=shownewArrayList(arrayList);
Iterator it=arrayList1.iterator();
while(it.hasNext()){
Person1 person=(Person1)it.next();
System.out.println(person.name+"::"+person.age);
}
}
private static ArrayList showArrayList(ArrayList arrayList) {
arrayList=new ArrayList();
arrayList.add(new Person1("张三",20));
arrayList.add(new Person1("李四",22));
arrayList.add(new Person1("王五",23));
arrayList.add(new Person1("赵六",24));
arrayList.add(new Person1("赵六",24));
return arrayList;
}
public static ArrayList shownewArrayList(ArrayList arrayList){
ArrayList newArrayList=new ArrayList();
Iterator iterator=arrayList.iterator();
while(iterator.hasNext()){
Object object=iterator.next();
if(!newArrayList.contains(object)){
newArrayList.add(object);
}
}
return newArrayList;
}
}
class Person1{
public String name;
public int age;
Person1(String name,int age){
this.name=name;
this.age=age;
}
/*public int hashCode(){
return name.hashCode()+age*27;
}*/
public boolean equals(Object object){
if(!(object instanceof Person1))
return false;
Person1 person=(Person1)object;
return this.name.equals(person.name)&&this.age==person.age;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2