本帖最后由 doyxy 于 2014-1-13 14:02 编辑
arraylist的练习,看着和毕老师的代码没什么区别,为什么运行会报错呢?
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:834)
at ArrayListTest2.getSingle(ArrayListTest2.java:69)
at ArrayListTest2.main(ArrayListTest2.java:50)
- /*
- list集合中判断元素是否相同,使用的是元素的equals方法
- */
- 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;
- }
- 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 ArrayListTest2
- {
- public static void main(String[] args)
- {
- ArrayList al = new ArrayList();
- al.add(new Person("lisi01",23));
- al.add(new Person("lisi02",25));
- al.add(new Person("lisi02",23));
- al.add(new Person("lisi03",32));
- al.add(new Person("lisi04",33));
- al.add(new Person("lisi04",33));
- al.add(new Person("lisi05",20));
- al = getSingle(al);
- Iterator it = al.iterator();
- while (it.hasNext())
- {
- Person p = (Person)it.next();//多态问题,需要向下转型.
- sop(p.getName()+"..."+p.getAge());
- }
- }
- public static ArrayList getSingle(ArrayList al)
- {
- ArrayList alnew = new ArrayList();
- //使用迭代器
- Iterator it = al.iterator();
- //历遍
- while (it.hasNext())
- {
- if (!alnew.contains(it.next()))
- alnew.add(it.next());
- }
- return alnew;
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码
|