例一
import java.util.*;
/*
去除ArrayList集合中的重复元素。
*/
class ArrayListTest
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add("java01");
al.add("java02");
al.add("java01");
al.add("java02");
al.add("java01");
// al.add("java03");
/*
在迭代时循环中next调用一次,就要hasNext判断一次。
Iterator it = al.iterator();
while(it.hasNext())
{
sop(it.next()+"...."+it.next());
}
*/
/**/
sop(al);
al = singleElement(al);
sop(al);
}
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;
}
}
例二
import java.util.*;
/*
将自定义对象作为元素存到ArrayList集合中,并去除重复元素。
比如:存人对象。同姓名同年龄,视为同一个人。为重复元素。
思路:
1,对人描述,将数据封装进人对象。
2,定义容器,将人存入。
3,取出。
List集合判断元素是否相同,依据是元素的equals方法。
*/
class Person
{
private String name;
private int age;
Person(String name,int age)
{
this.name = name;
this.age = 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;
}
/**/
public String getName()
{
return name;
}
public int getAge()
{
return 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(new Demo());
al.add(new Person("lisi01",30));//al.add(Object obj);//Object obj = new Person("lisi01",30);
//al.add(new Person("lisi02",32));
al.add(new Person("lisi02",32));
al.add(new Person("lisi04",35));
al.add(new Person("lisi03",33));
//al.add(new Person("lisi04",35));
//al = singleElement(al);
sop("remove 03 :"+al.**remove**(new Person("lisi03",33)));//remove方法底层也是依赖于元素的equals方法。
/*
public boolean **remove**(Object o)移除此列表中首次出现的指定元素(如果存在)。如果列表不包含此元素,
则列表不做改动。更确切地讲,移除满足 (o==null ? get(i)==null : o.**equals**(get(i))) 的最低索引的元素
(如果存在此类元素)。如果列表中包含指定的元素,则返回 true(或者等同于这种情况:如果列表由于调用而发生更改,
则返回 true)。
*/
Iterator it = al.iterator();
while(it.hasNext())
{
Person p = (Person)it.next();
sop(p.getName()+"::"+p.getAge());
}
}
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);
/*public boolean **contains**(Object o)如果此列表中包含指定的元素,则返回 true。
更确切地讲,当且仅当此列表包含至少一个满足 (o==null ? e==null : o.**equals**(e)) 的元素 e 时,
则返回 true。
*/
}
return newAl;
}
}