本帖最后由 王德升 于 2012-6-20 09:08 编辑
class Person
{
private String name;
private int age;
Person(String name,int age)
{
this.name = name;
this.age = age;
}
public boolean equals(Object obj)// 3.
{
if(!(obj instanceof Person))// 1.
return false;
Person p = (Person)obj;
return this.name.equals(p.name) && this.age == p.age;// 2.
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
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;
}
class ArrayListTest
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add(new Person("lisi01",30));
al.add(new Person("wangwu02",32));
al.add(new Person("lisi04",35));
al.add(new Person("wangwu02",32));
sop("remove 03 :"+al.remove(new Person("lisi03",33)));
Iterator it = al.iterator();
while(it.hasNext())
{
Person p = (Person)it.next();
sop(p.getName()+".........."+p.getAge());
}
}
}
1.老师说这里可以抛出异常请问代码是怎么写的?
2.这里第一个equals是字符串name的.
3.这个是Person的equals方法,
那么2和3这2个equals怎么区别呢,尤其是第2个equals. |
|