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))
&& (lastName.equals(name.lastName));
}
return super.equals(obj);
}
public int hashCode() {
return firstName.hashCode();// 这个地方为什么只有firstName.hashCode()。我感觉还要有个lastName.hashCode();
}
public int compareTo(Object o) {
Name n = (Name)o;
int lastCmp =
lastName.compareTo(n.lastName);
return
(lastCmp!=0 ? lastCmp :
firstName.compareTo(n.firstName));
}
}
还有就是重写equals到底要做什么?为什么重写equals就要重写hashCode
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))
&& (lastName.equals(name.lastName));
}
return super.equals(obj);
}
public int hashCode() {
return firstName.hashCode();// 这个地方为什么只有firstName.hashCode()。我感觉还要有个lastName.hashCode();
}
public int compareTo(Object o) {
Name n = (Name)o;
int lastCmp =
lastName.compareTo(n.lastName);
return
(lastCmp!=0 ? lastCmp :
firstName.compareTo(n.firstName));
}
}
还有就是重写equals到底要做什么?为什么重写equals就要重写hashCode
简单点就是 eqauls 相当于 == hashCode就是生成一串代表符代表这个集合的内容,
就比如: 一个软件需要用到 账号 密码 其实密码为了不让所谓的网管看到,都是把密码生成一种hashCode。。来进行保存,等你第二次进入时就把你输入的密码在hashCode一次生成的与你注册的放在数据库中的hashCode相比较 但是有种情况就是这种 :A: 2+1+4=7;B: 2+2+3=7;他们生成的hashCode都是7那么出现了重码也就是== 但是他们前面的属性其实是不同的。
你只要记住如果你要用eqauls比较时你要覆盖Sun公司提供的eqauls同时必须覆盖hashCode!这样才能按照我们程序员的思路走