在看老毕的视频,看到arraylist的练习的时候,有一个例子是将人的对象装进容器中,然后去除姓名和年龄相同的对象。视频中讲contains底层默认调用equals方法(下面代码的红色部分),可是equals是非静态的,而 singleElenment()是静态的方法,所以就相当与在静态中调用了非静态的方法equals(),其源代码如下:
import java.util.*;
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;
return this.name.equals(p.name)&&this.age==p.age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class ArrayListDemo2
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add(new Person("lisi01",31));
al.add(new Person("lisi02",32));
al.add(new Person("lisi03",33));
al.add(new Person("lisi04",34));
al.add(new Person("lisi04",34));
al=singleElement(al);
Iterator it=al.iterator();
while(it.hasNext())
{
Person p=(Person)it.next();
sop(p.getName()+"..."+p.getAge());
}
}
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)))//默认调用equals,而equals是非静态,怎么能在静态函数中调用呢??
newAl.add(obj);
}
return newAl;
}
public static void sop(Object obj)
{
System.out.println(obj);
}
}
|