本帖最后由 ~IN_HAND~ 于 2013-10-27 23:50 编辑
并不是什么大问题,但是我始终没搞明白。。。下面这个程序是利用ArrayList集合不断增加元素,重复的元素要筛选掉。
废话不多说,直接上代码import java.util.*;
class ArrayListTest0
{
public static void main(String[] args)
{
ArrayList a1 = new ArrayList();
a1.add(new Person("jia",23));
a1.add(new Person("jia",22));
a1.add(new Person("zheng",22));
a1.add(new Person("jia",23));
a1 = singleElements(a1);
//问题就出在这个地方了,调用此方法,在程序的输出结果中就会输出Person类中equals方法中的那句话,
//但是,令我费解的是,如果不调用此方法的话,为什么就不调用equals方法了呢?输出中没有啊?!
//我对equals的理解,集合在增加元素时会调用equals方法,我理解错了吗?
Iterator it = a1.iterator();
while(it.hasNext())
{
Person p = (Person)it.next();
String name = p.getName();
int age = p.getAge();
System.out.println("name: "+name+" "+"age: "+age);
}
}
public static ArrayList singleElements(ArrayList list)
{
ArrayList ls = new ArrayList();
Iterator it = list.iterator();
while(it.hasNext())
{
Object obj = it.next();
if(!ls.contains(obj))
ls.add(obj);
}
return ls;
}
}
class Person
{
private String name;
private int age;
public 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;
System.out.println(this.name+"......."+p.name);
return this.name.equals(p.name) && this.age == p.age;
}
}
求高人指点迷津!!!
|