//去除ArrayList中重复的元素
//同名同年龄视为同一个人。
import java.util.*;
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;
}
//复写Object中的equals方法,来确定同名同年龄为同一个人
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;
}
}
class ArrayListText2
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static ArrayList singleElementArrayList(ArrayList al)
{
ArrayList newAl = new ArrayList();
for(Iterator it = al.iterator(); it.hasNext();)
{
Object obj = it.next();
//Person p = (Person)obj;
if(!(newAl.contains(obj)))
newAl.add(obj);
/*
if(!(newAl.contains(it.next())))
newAl.add(it.next());
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:794)
at ArrayListText2.singleElementArrayList(ArrayListText2.java:45)
at ArrayListText2.main(ArrayListText2.java:66)
*/
}
return newAl;
}
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add(new Person("zhangsan01",21));
al.add(new Person("zhangsan02",21));
al.add(new Person("zhangsan02",24));
al.add(new Person("zhangsan01",21));
al.add(new Person("zhangsan03",23));
for(Iterator it = al.iterator(); it.hasNext();)
{
Person p = (Person)it.next();
System.out.println(p.getName()+" "+p.getAge());
}
al = singleElementArrayList(al);
System.out.println();
for(Iterator it = al.iterator(); it.hasNext();)
{
Person p = (Person)it.next();
System.out.println(p.getName()+" "+p.getAge());
}
}
}
为什么 /*
if(!(newAl.contains(it.next())))
newAl.add(it.next());
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:794)
at ArrayListText2.singleElementArrayList(ArrayListText2.java:45)
at ArrayListText2.main(ArrayListText2.java:66)
*/会抛出异常?
|