- <P>public static ArrayList singleElement(ArrayList al)
- {
- ArrayList newAl = new ArrayList();
- Iterator it = al.iterator();
- while(it.hasNext())
- {
- /*</P>
- <P>建立一个Object对象引用,用来接收it.next()返回的对象,
- Object obj = it.next();
- if(!newAl.contains(obj))
- newAl.add(obj);
- */</P>
- <P> </P>
- <P>/*</P>
- <P>此处
- 没有建立Object对象引用,编译通过,运行时得不到预想的答案。
- if(!newAl.contains(it.next()))
- newAl.add(it.next());
- }
- */
- return newAl;
- }</P>
复制代码
以下为源码。- import java.util.*;
- /*
- 去除ArrayList集合中重复的元素
- */
- class ArrayListDemo
- {
- public static void main(String[] args)
- {
- ArrayList al = new ArrayList();
- al.add("java01");
- al.add("java03");
- al.add("java01");
- al.add("java02");
- al.add("java03");
- al.add("java01");
- sop("判断之前====="+al);
- al = singleElement(al);
- sop("判断之后:::"+al);
- }
- 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);
- */
- if(!newAl.contains(it.next()))
- newAl.add(it.next());
- }
- return newAl;
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码 |