集合部分,去除集合中重复的对象,为什么要在Person中重写equals方法
代码如下:
- package com.test2;
- import java.util.*;
- class Person{
- private String name ;
- private int age;
- Person(String name,int age){
- this.name = name;
- this.age = age;
- }
- <font color="Red">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;
-
- }</font>
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- }
- public class CollectionDemo {
-
- public static void main(String[] args) {
- ArrayList al = new ArrayList();
-
- al.add(new Person("lisi01",21));//add(Object obj);>>>Object obj = new Person("lisi01",21)
- al.add(new Person("lisi02",22));
- al.add(new Person("lisi04",24));
- al.add(new Person("lisi03",23));
- al.add(new Person("lisi04",24));
- al.add(new Person("lisi02",22));
- al.add(new Person("lisi04",24));
-
- Iterator it = singleElement(al).iterator();
-
- while(it.hasNext()){
- Person p =(Person) it.next();
- sop(p.getName()+"---"+p.getAge());
- }
-
-
- }
-
- public static void sop(Object obj){
- System.out.println(obj);
- }
- //去除重复对象
- public static ArrayList singleElement(ArrayList al){
- //定义一个临时容器
- ArrayList alNew = new ArrayList();
- Iterator it = al.iterator();
- while(it.hasNext()){
- Object obj = it.next();
- if(!alNew.contains(obj))
- alNew.add(obj);
- }
- return alNew;
- }
- }
复制代码
|
|