- package qbb;
- import java.util.*;
- public class ArrayListTest {
- 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 main(String[] args) {
- ArrayList al = new ArrayList();
- al.add("java1");
- al.add("java2");
- al.add("java1");
- al.add("java2");
- al.add("java3");
- System.out.println(al);
- al = singleElement(al);
- System.out.println(al);
- }
- }
复制代码 运行结果:
[java1, java2, java1, java2, java3]
[java1, java2, java3]- package qbb;
- 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 class ArrayListTest2 {
- 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 main(String[] args) {
- ArrayList al = new ArrayList();
- al.add(new Person("Lisi01",30));
- al.add(new Person("Lisi02",32));
- al.add(new Person("Lisi02",32));
- al.add(new Person("Lisi03",33));
- al.add(new Person("Lisi04",33));
- al.add(new Person("Lisi04",33));
- System.out.println(al);
- al = singleElement(al);
- System.out.println(al);
- }
- }
复制代码 运行结果:
[qbb.Person@1b60280, qbb.Person@5e55ab, qbb.Person@14a55f2, qbb.Person@15093f1, qbb.Person@120bf2c, qbb.Person@e6f7d2]
[qbb.Person@1b60280, qbb.Person@5e55ab, qbb.Person@14a55f2, qbb.Person@15093f1, qbb.Person@120bf2c, qbb.Person@e6f7d2]
调用的方法一样,
为什么第一个可以过滤重复,第二个却不可以呢?
|