本帖最后由 2528870651 于 2014-6-17 15:55 编辑
假如你要存入list集合的是一个Person对象,那么在Person类里面重写equals函数,如:
- 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;
- }
复制代码
然后你可以自己根据上面的函数再写个函数,再来删除
这是我上午写的程序,我也在学这里,
- package it.heima.com.collection;
- import java.util.ArrayList;
- import java.util.Iterator;
- /*
- 将自定义对象作为元素存到ArrayList集合中,并去除重复元素。
- 比如:存人对象。同姓名同年龄,视为同一个人。为重复元素。
- 思路:
- 1,对人描述,将数据封装进人对象。
- 2,定义容器,将人存入。
- 3,取出。
- List集合判断元素是否相同,依据是元素的equals方法。
- */
- public class ArrayListTest {
- public static void main(String[] args){
- ArrayList<Person> al = new ArrayList<Person>();
- al.add(new Person());
- al.add(new Person("zhangsan01",20));
- al.add(new Person("zhangsan02",21));
- al.add(new Person("zhangsan03",22));
- al.add(new Person("zhangsan04",23));
- al.add(new Person("zhangsan05",24));
- al.add(new Person("zhangsan01",20));
- al = singleElement(al);
- Iterator<Person> it = al.iterator();
- while(it.hasNext()){
- Person p = (Person)it.next();
- sop(p.getName()+"::"+p.getAge());
- }
-
- }
- public static ArrayList<Person> singleElement(ArrayList<Person> al){
- //定义一个临时容器。
- ArrayList<Person> newAl = new ArrayList<Person>();
- Iterator<Person> it = al.iterator();
- while(it.hasNext()){
- Person p = it.next();
- if(!newAl.contains(p))
- newAl.add(p);
- }
- return newAl;
- }
-
- public static void sop(Object obj){
- System.out.println(obj);
- }
- }
复制代码- package it.heima.com.collection;
- public class Person {
- private String name;
- private int age;
-
- Person(){
-
- }
- Person(String name, int age){
- this();
- 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;
- }
-
- 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;
- }
-
- }
复制代码
|