首先写一个Person类:[code=java]package org.cxy.demo;
public 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 void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return "姓名:"+this.name+",年龄:"+this.age;
}
}[/code]然后要知道,调用List的remove(Object)方法,删除自定义类时,需要为咱们的自定义类重写equals方法。
范例1:看看如下代码。[code=java]package org.cxy.demo;
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
list.add(new Person("张三",30));
System.out.println("删除之前:"+list);
list.remove(new Person("张三",30));
System.out.println("删除之后:"+list);
}
}[/code]但是,由于没有为Person类重写equals方法,而是自动调用的Object类的equals方法,因此,删除失败。
范例2:使用如下代码,可以删除成功。[code=java]package org.cxy.demo;
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<Person> list = new ArrayList<Person>();
Person p = new Person("张三",30);
list.add(p);
System.out.println("删除之前:"+list);
list.remove(p);
System.out.println("删除之后:"+list);
}
}[/code]因为Object类的equals方法,源代码:[code=java] public boolean equals(Object obj) {
return (this == obj);
}[/code]因此,您可以为Person重写equals方法,然后执行范例1,就可以删除成功了。
范例3:重写equals。[code=java]package org.cxy.demo;
public 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 void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object obj){
if(this == obj){
return true;
}
if(!(obj instanceof Person)){
return false;
}
Person p = (Person)obj;
if(this.age == p.age && this.name.equals(p.name)){
return true;
}
return false;
}
public String toString(){
return "姓名:"+this.name+",年龄:"+this.age;
}
}[/code] |