你们回答都不全面,大家注意他的al.remove(new Person("lisi2",22))方法
- import java.util.ArrayList;
- import java.util.Iterator;
- class Person
- {
- private String Person;
- private int age;
- @Override
- public String toString()
- {
- return this.Person+":"+this.age;
- }
- public Person(String person,int age)
- {
- this.Person=person;
- this.age=age;
- }
- public String getPerson() {
- return Person;
- }
- public void setPerson(String person) {
- Person = person;
- }
- public boolean equals(Object obj)
- {
- Person person=(Person)obj;
- if(this.age==person.age&&this.Person!=null
- &&this.Person.equalsIgnoreCase(person.Person))
- return true;
- else
- return false;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
- public class fd
- {
- public static void main(String[] args) {
- ArrayList<Object> al = new ArrayList<Object>();
- al.add(new Person("lisi1",21));
- al.add(new Person("lisi2",22));
- al.add(new Person("lisi3",23));
- al.add(new Person("lisi4",24));
- al.add(new Person("lisi2",22));
- al.add(new Person("lisi3",23));
- System.out.println(al);
-
- al = getSingleElement(al);
-
- System.out.println(al.remove(new Person("lisi2",22)));
- System.out.println(al);
- }
- public static ArrayList getSingleElement(ArrayList al) {
-
- //1,定义一个临时容器。
- ArrayList temp = new ArrayList();
-
- //2,迭代al集合。
- Iterator it = al.iterator();
-
- while(it.hasNext()){
- Object obj = it.next();
-
- //3,判断被迭代到的元素是否在临时容器存在。
- if(!temp.contains(obj)){
- temp.add(obj);
- }
- }
-
- return temp;
- }
- }
复制代码
[lisi1:21, lisi2:22, lisi3:23, lisi4:24, lisi2:22, lisi3:23]
true
[lisi1:21, lisi3:23, lisi4:24] |