将自定义对象作为元素存到ArrayList集合中,并去除重复元素。
比如:存人对象。同姓名同年龄,视为同一个人。为重复元素。
思路:
1,对人描述,将数据封装进人对象。
2.定义容器,将人存入。
3.取出。
List 集合判断元素是否相同,依据是元素equals方法。contains、remove底层调用的都是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;
}
//复写Object的equals,Object中的equals是判断地址值是否相同。
public boolean equals(Object obj)
{
//System.out.println(this.name+"....."+this.name);
//instanceof 运算符只能用作对象的判断。
if(!(obj instanceof Person))
{
return false;
}
Person p = (Person)obj;
return this.name.equals(p.name)&& this.age ==p.age;
}
}
class ArrayListTest2
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add(new Person("lisi01",30));//al.add(Object obj);//Object obj = new Person("lisi01",30);
al.add(new Person("lisi02",31));
al.add(new Person("lisi02",31));
al.add(new Person("lisi03",33));
al.add(new Person("lisi04",35));
al.add(new Person("lisi04",35));
//al = singleElement(al);
sop("remove 03:"a1.remove(new Person("lisi03",33)));
Iterator it = al.iterator();
while (it.hasNext())
{
/*
向下转型:强转
Object obj = it.next();
Person p = (Person)Obj;
*/
Person p = (Person)it.next();
sop(p.getName()+"::::"+p.getAge());
}
}
public static ArrayList singleElement(ArrayList al)
{
//定义一个临时容器
ArrayList newal = new ArrayList();
Iterator it = newal.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);
}
}
网友评论