// One practice
package Collection; import java.util.ArrayList;
import java.util.Iterator; // 去除 ArrayList 集合中的重复元素
public class ArrayListTest
{
public static void sop(Object obj)
{
System.out.println(obj);
} public static void main(String[] args)
{
ArrayList<String> arrayList = new ArrayList<String>(); arrayList.add("java01");
arrayList.add("java02");
arrayList.add("java03");
arrayList.add("java04");
arrayList.add("java01");
arrayList.add("java02");
arrayList.add("java03"); sop(arrayList);
arrayList = singleElement(arrayList);
sop(arrayList); } public static ArrayList<String> singleElement(ArrayList<String> al)
{
// 定义一个临时容器
ArrayList newAl = new ArrayList();
Iterator iterator = al.iterator();
while (iterator.hasNext())
{
Object obj = iterator.next();
if (!newAl.contains(obj))
{
newAl.add(obj);
}
}
return newAl;
}
} // Practice Two package Collection; import java.util.ArrayList;
import java.util.Iterator; // 将自定义对象作为元素存到 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;
}
// 重写 equals 方法
public boolean equals(Object obj)
{
if (!(obj instanceof Person))
{
return false;
}
Person person = (Person)obj;
return this.name.equals(person.name) && this.age == person.age;
} public String getname()
{
return name;
}
public int getage()
{
return age;
} } public 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 Person("Xp01", 30));
al.add(new Person("Xp02", 35));
al.add(new Person("Xp02", 35));
al.add(new Person("Xp03", 37));
al.add(new Person("Xp04", 35));
al.add(new Person("Xp04", 35)); al = singleElement(al); Iterator it = al.iterator(); while (it.hasNext())
{
Person p = (Person)it.next();
sop(p.getname()+"::"+p.getage());
}
} public static ArrayList singleElement(ArrayList<String> al)
{
// 定义一个临时容器
ArrayList newAl = new ArrayList();
Iterator iterator = al.iterator();
while (iterator.hasNext())
{
Object obj = iterator.next();
if (!newAl.contains(obj))
{
newAl.add(obj);
}
}
return newAl;
}
}