本帖最后由 王得新 于 2012-9-27 10:08 编辑
今天看了毕老师关于集合的视频,其中讲到ArrayList中equals()方法,有点困惑!!先上代码:
public class Person {
private String name;
private int age;
Person(String name,int age){
this.name=name;
this.age=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;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
}
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList al=new ArrayList();
al.add(new Person("lisi1",21));
al.add(new Person("lisi2",25));
al.add(new Person("lisi2",25));
al.add(new Person("lisi3",22));
al.add(new Person("lisi4",26));
al.add(new Person("lisi4",26));
al=singleEnevent(al);//去除重复元素,在这个方法中,有一个contains()方法,contains()方法又调用了equals()方法
//疑惑来了,就是equals(Object obj)方法中的参数,obj是怎么回事,是怎么调用的,我就是contains()方法中调用equals()转不过来?
//求高手解答!!!!
Iterator it=al.iterator();
while(it.hasNext()){
Person ps=(Person) it.next();
System.out.println(ps.getName()+"::"+ps.getAge());
}
}
public static ArrayList singleEnevent(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;
}
}
|