ArrayList 去除重复元素

import java.util.*;
class ArrayListDemo
{
    public static void main(String[] args)
    {
        ArrayList arr=new ArrayList();
        arr.add("java01");
        arr.add("java01");
        arr.add("java02");
        arr.add("java03");
        arr.add("java01");
        arr.add("java05");
        sop(arr);
        arr=SingleElement(arr);    
        sop(arr);
    }
    public static ArrayList SingleElement(ArrayList al)
    {
        ArrayList newal=new ArrayList();
        Iterator it=al.iterator();
        while(it.hasNext())
        {
            Object obj=it.next();
            if(!newal.contains(obj))
                    newal.add(obj);
        
        }
        return newal;
    }
    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

去除重复的对象 除非名字和姓名不一样 才可以存入

import java.util.*;
class ArrayListDemo
{
    public static void main(String[] args)
    {
        ArrayList arr=new ArrayList();
        arr.add(new person("01",22));
        arr.add(new person("02",22));
        arr.add(new person("01",22));
        arr.add(new person("02",22));
        arr.add(new person("01",22));
        arr=SingleElement(arr);
        Iterator it=arr.iterator();
        while(it.hasNext())
        {
            person obj=(person)it.next();
            System.out.println(obj.getName()+" "+obj.getAge());
        }
    }
    public static ArrayList SingleElement(ArrayList al)
    {
        ArrayList newal=new ArrayList();
        Iterator it=al.iterator();
        while(it.hasNext())
        {
            Object obj=it.next();
            if(!newal.contains(obj))
                    newal.add(obj);
        
        }
        return newal;
    }
    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}
class person
{
    private String name;
    private int age;
    person(String name,int age)
    {
        this.name=name;
        this.age=age;
    }
    public String getName()
    {
        return name;
    }
    public int getAge()
    {
        return 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;
    }
}

posted on 2012-11-15 09:52  蝌蚪的精神  阅读(256)  评论(0编辑  收藏  举报

导航