本帖最后由 思维 于 2014-8-24 16:58 编辑
今天写了一个集合去除重复元素的代码!为什么得不到正确的结果啊?- import java.util.*;
- class Person{
- private String name;
- private int age;
- Person(String name,int age){
- this.name = name;
- 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;
- }
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- }
- class Test{
- public static void main(String[] args){
- ArrayList<Person> al = new ArrayList<Person>();
- al.add(new Person("zhangsan",19));
- al.add(new Person("lisi",32));
- al.add(new Person("wangwu",12));
- al.add(new Person("zhangsan",19));
- Iterator<Person> it = al.iterator();
- while(it.hasNext()){
- Person p = (Person)it.next();
- System.out.println(p.getName()+"..."+p.getAge());
- }
- System.out.println("---------------------");
- ArrayList<Person> newAl = singleElement(al);
- Iterator ite = newAl.iterator();
- while(ite.hasNext()){
- Person p = (Person)ite.next();
- System.out.println(p.getName()+"..."+p.getAge());
- }
- }
- private static ArrayList<Person> singleElement(ArrayList<Person> al){
- ArrayList<Person> newAl = new ArrayList<Person>();
- Iterator<Person> it = al.iterator();
- while(it.hasNext()){
- Person p = (Person)it.next();
- if(!newAl.contains(p)){
- newAl.add(p);
- }
- }
- return newAl;
- }
- }
复制代码
|