本帖最后由 陈忠 于 2012-4-26 20:57 编辑
import java.util.ArrayList;
import java.util.List;
public class TestCollection {
public static void main(String[] args){
List<Name> list = new ArrayList<Name>();
Name name = new Name("aa","nbb");
list.add(new Name("zhang","san"));
list.add(new Name("li","si"));
list.add(new Name("wang","wu"));
list.add(name);
System.out.println(list.remove(new Name("zhang","san")));//为什么这里输出的是false
System.out.println(list.remove(name));//用name的时候就是true
System.out.println(list.contains(new Name("wang","wu")));//为什么这里输出的是false
System.out.println(list);
}
}
class Name implements Comparable<Name> {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Name(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String toString() {
return firstName+" "+lastName;
}
public int compareTo(Name name) {
int compare = firstName.compareTo(name.firstName);
return compare!=0?compare:lastName.compareTo(name.lastName);
}
public boolean equals(Name name) {
return (firstName.equals(name.firstName))
&&(lastName.equals(name.lastName));
}
public int hashCode() {
return firstName.hashCode();
}
} |