第一。
import java.util.*;
public class BasicContainer {
public static void main(String[] args) {
Collection c = new HashSet();
c.add("hello");
c.add(new Name("f1","l1"));
c.add(new Integer(100));
c.remove("hello");
c.remove(new Integer(100));
System.out.println
(c.remove(new Name("f1","l1")));
System.out.println(c);
}
}
class Name implements Comparable {
private String firstName,lastName;
public Name(String firstName, String lastName) {
this.firstName = firstName; this.lastName = lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String toString() { return firstName + " " + lastName; }
public boolean equals(Object obj) {
if (obj instanceof Name) {
Name name = (Name) obj;
return (firstName.equals(name.firstName))//老毕在这里写的是this.firstName.... 和this.lastName,this是可以省略的,可是2个一对比我
//我就看不懂了,麻烦大神给我讲讲调用的过程。
&& (lastName.equals(name.lastName));
}
return super.equals(obj);//这里讲解的老师说Object的equals方法就是==,我不大懂,这里返回的是父类的equals方法是怎么去实现的不要返回false?
}
public int hashCode() {
return firstName.hashCode();//这里为什么只判断了firstName为什么没有判断lastName?
}
public int compareTo(Object o) {
Name n = (Name)o;
int lastCmp =
lastName.compareTo(n.lastName);
return
(lastCmp!=0 ? lastCmp :
firstName.compareTo(n.firstName));
}
}
第二。
equals方法和hashCode老毕说是先判断hashCode再判断equals,但是我今天看到的是先判断hashCode然后再判断equals,当时我就蒙了,
谁知道这到底是怎么样的? 还有就是说hashCode什么时候会使用?就是当对象被当做某个键当做索引的时候才会被用到?怎么理解呢???
|