我自己用循环写的。
- import java.util.ArrayList;
- public class ArrayListTest2 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- ArrayList al = new ArrayList();
- al.add(new Person("zhangsan",20));
- al.add(new Person("lisi",21));
- al.add(new Person("wangwu",22));
- al.add(new Person("zhaoliu",23));
-
-
-
- al.add(new Person("lisi",21));
- al.add(new Person("wangwu",22));
- al.add(new Person("zhaoliu",23));
-
-
- System.out.println(al);
-
-
- single(al);
- System.out.println(al);
-
-
-
- }
- public static void single(ArrayList al)
- {
- if(al.isEmpty())
- System.out.println("传入数组为空,请检查");
- else
- for(int i = 0 ; i<al.size()-1;i++)
- {
- for(int j = i+1;j<al.size();j++)
- {
- if(al.get(i).equals(al.get(j)))//循环中。如果equals值相等就删除元素
- al.remove(j);
- }
-
- }
-
-
-
- }
- }
- class Person
- {
- String name;
- int age;
- public Person(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- public boolean equals(Object obj)
- {
-
- if(!(obj instanceof Person))
- return false;
-
- Person p = (Person)obj;
- return this.age == p.age && this.name.equals(p.name);
-
- }
- public String toString()
- {
- return name+" "+age;
- }
- }
复制代码
当if(al.get(i).equals(al.get(j)))//循环中。如果equals值相等就删除元素
al.remove(i);
不能正确删除最后一个重复的对象为什么。实在是想不明白 |