标签:
要求:去除ArrayList集合中的重复元素
import java.util.*;
class ArrayListTest
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add("1");
al.add("2");
al.add("1");
al.add("2");
al.add("1");
al.add("3");
al.add("4");
al.add("1");
sop(al);
ArrayList newAl = singleElement(al);
sop(newAl);
System.out.println("Hello world!");
//在迭代时循环中的next调用一次,就要hasNext判断一次
}
public static ArrayList singleElement(ArrayList al)
{
ArrayList newAl = new ArrayList();
Iterator it = al.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(!newAl.contains(obj))
{
newAl.add(obj);
}
}
return newAl;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
[1, 2, 1, 2, 1, 3, 4, 1]
[1, 2, 3, 4]
Hello world!
举例:
//List集合判断元素是否相同,依据是元素的equals方法
import java.util.*;
class Person
{
private String name;
private int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
return false;
Person p = (Person)obj;
System.out.println(this.name+"......"+p.name);
return this.name.equals(p.name)&&this.age==p.age;
}
}
class ArrayListTest2
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
ArrayList al = new ArrayList();
//al.add(Object obj); Object obj = new Person("zhangsan",30);
al.add(new Person("zhangshan",20));
al.add(new Person("lisi",22));
al.add(new Person("wangwu",23));
al.add(new Person("wangwu",23));
al.add(new Person("alex",24));
al.add(new Person("alex",24));
al = singleElemenet(al);
sop("remove"+al.remove(new Person("alex",24)));
Iterator it = al.iterator();
while(it.hasNext())
{
Person p =(Person)it.next();
sop(p.getName()+"::"+p.getAge());
}
}
public static ArrayList singleElemenet(ArrayList al)
{
ArrayList newAl = new ArrayList();
Iterator it = al.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(!newAl.contains(obj))
{
newAl.add(obj);
}
}
return newAl;
}
lisi……zhangshan
wangwu……zhangshan
wangwu……lisi
wangwu……zhangshan
wangwu……lisi
wangwu……wangwu
alex……zhangshan
alex……lisi
alex……wangwu
alex……zhangshan
alex……lisi
alex……wangwu
alex……alex
alex……zhangshan
alex……lisi
alex……wangwu
alex……alex
removetrue
zhangshan::20
lisi::22
wangwu::23
标签:
原文地址:http://blog.csdn.net/jungle_hello/article/details/51330736