import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo2_1 {
public static void main(String[] args) {
// 创建容器,添加数据
ArrayList al = new ArrayList();
al.add(new Person("wangba01", 11));
al.add(new Person("wangba03", 13));
al.add(new Person("wangba02", 12));
al.add(new Person("wangba01", 11));
al.add(new Person("wangba06", 16));
// 调用去重代码块,对al去重
al = go(al);
// 通过迭代器,遍历所有元素
Iterator it = al.iterator();
while (it.hasNext()) {
// 将al中的元素强转成Person类型,因为al中默认是Object类型;必须将object向下转型成Person,这样才能调用
// person中的getName()和getAge();
Person p = (Person) it.next();
sop(p.getName() + "....." + p.getAge());
// 当调用两次next()时,两次锁指向的并不是同一个元素,第二个next()是第一个next()的后面一个;
// 也就是说,调用此行代码时,从al中是一次性取两个数
// sop(it.next().getName()+"..."+it.next().getAge());
}
}
// 去重代碼
public static ArrayList go(ArrayList al) {
// 创建一个临时容器
ArrayList newAl = new ArrayList();
// 使用迭代器遍历传进来的al
Iterator it = al.iterator();
while (it.hasNext()) {
Object object = it.next();
// 判断当newAl中是否有相同的元素
// 如果newAl中不包含object;那么就将object放入newAl中
if (!newAl.contains(object))
newAl.add(object);
}
return newAl;
}
// 打印代码块
public static void sop(Object object) {
System.out.println(object);
}
}
class Person {
// Person方法默认继承Object的equals方法。
// Object 类的 equals 方法实现对象上差别可能性最大的相等关系;即,对于任何非空引用值 x 和 y,当且仅当 x 和 y
// 引用同一个对象时,此方法才返回 true(x == y 具有值 true)。
// 主函数中,运用new运算符创建Person对象,其内存地址不一样,所以当person调用object的equals方法时,进行地址比较,返回的仍是false;
// 所以必须重写object的equals()方法
private String name;
private int age;
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
Person p = (Person) obj;
return this.name.equals(p.name) && this.age == p.age;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
ArrayList 集合框架实例(数据去重)
最新推荐文章于 2023-08-20 19:02:43 发布