import java.util.ArrayList;
import java.util.Iterator;
/**
* 1.去重复 思路: 将一个ArrayList传进来,创建一个临时容器,对比有重复则不存。<br>
*
* 2.去重复对象 比如人,同姓名,同年龄视为一个人 思路 封装人对象存入集合
* */
public class ArrayListNoRepeatTest {
public static ArrayList singleArrayList(ArrayList al) {
ArrayList newal = new ArrayList();
for (Iterator it = al.iterator(); it.hasNext();) {
Object obj = it.next();
if (!newal.contains(obj))
newal.add(obj);
}
return newal;
}
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add("java0");
al.add("java1");
al.add("java2");
al.add("java0");
al.add("java1");
// al.add("java2");//[☆]元素为偶数时没事,奇数是发生异常
// System.out.println(al);
System.out.println(singleArrayList(al));
for (Iterator it = al.iterator(); it.hasNext();) {
System.out.println(it.next() + "...."/* +it.next() */);// [☆]在迭代器中,next调用一次,就要判断一次
}
ArrayList all = new ArrayList();
all.add(new Person("zhangsan", 30));
all.add(new Person("lisi", 25));
all.add(new Person("zhangsan", 25));
all.add(new Person("zhangsan", 30));
all = singleArrayList(all);
for (Iterator it = all.iterator(); it.hasNext();) {
Person p = (Person) it.next();
System.out.println(p.getName() + "..." + p.getAge());
}
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
Person p = (Person) obj;
System.out.println(this.getName() + this.getAge() + ".equals."
+ p.getName() + p.getAge());
return this.name.equals(p.name) && this.age == p.age;
}
@Override
public int hashCode() {
System.out.println(this.getName() + this.getAge() + ".hashCode.");
return name.hashCode() + age * 39;
}
}
//LinkedList和vector都是List的子类,方法相似,
//同时要想在存入是就保证元素的唯一性,需要用到Set集合接口
|