- /*需求:去除对象中的重复元素*/
- import java.util.*;
- class Person
- {
- private String name;
- private int age;
- public Person(String name,int age){
- this.name = name;
- this.age = age;
- }
- //使用list集合时,想要去除对象中的重复元素,必须复写equals(Object obj)
- public boolean equals(Object obj){
- System.out.println("++++++++++");
- if(!(obj instanceof Person))
- throw new RuntimeException();
- Person p = (Person) obj;
- return true;
- }
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- }
- class DemoTest3
- {
- public static void main(String[] args)
- {
- ArrayList list = new ArrayList();
- list.add(new Person("li01",12));
- list.add(new Person("li01",12));
- list.add(new Person("li01",12));
- list.add(new Person("li01",12));
- list.add(new Person("li01",12));
- for(Iterator it=list.iterator();it.hasNext();){
- Person p =(Person)it.next();
- System.out.println(p.getName());
- }
- }
- }
复制代码 这是什么情况??? 真的很纳闷 求高手指教
|
|