import java.util.*;
public class TestCollection {
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("Hello");
c.add(new Worker("royzhou","22"));
c.add(new Integer(100));
c.remove("Hello");
c.remove(new Integer(100));
c.remove(new Worker("royzhou","22"));
System.out.println(c);
}
}class Worker {
String name;
String age;
Worker(String name, String age) {
this.name = name;
this.age = age;
}
public String toString() {
return name+" "+age;
}
public boolean equals(Object obj) {
if(obj instanceof Worker) {
Worker worker =(Worker) obj;
return((name.equals(worker.name))&&(age.equals(worker.age)));
}
return super.equals(obj);
}
public int hashCode() {
return name.hashCode();
}}程序里面hashCode()有什么用 ,在这里需要吗?
public class TestCollection {
public static void main(String[] args) {
Collection c = new ArrayList();
c.add("Hello");
c.add(new Worker("royzhou","22"));
c.add(new Integer(100));
c.remove("Hello");
c.remove(new Integer(100));
c.remove(new Worker("royzhou","22"));
System.out.println(c);
}
}class Worker {
String name;
String age;
Worker(String name, String age) {
this.name = name;
this.age = age;
}
public String toString() {
return name+" "+age;
}
public boolean equals(Object obj) {
if(obj instanceof Worker) {
Worker worker =(Worker) obj;
return((name.equals(worker.name))&&(age.equals(worker.age)));
}
return super.equals(obj);
}
public int hashCode() {
return name.hashCode();
}}程序里面hashCode()有什么用 ,在这里需要吗?
从此 collection 中移除指定元素的单个实例,如果存在的话(可选操作)。更正式地说,如果此 collection 包含一个或多个满足 (o==null ? e==null : o.equals(e)) 的元素 e,则移除这样的元素。如果此 collection 包含指定的元素(或者此 collection 随调用的结果而发生改变),则返回 true。 参数:
o - 要从此 collection 中移除的元素(如果存在)。
返回:
如果此 collection 随调用的结果而发生改变,则返回 true
抛出:
ClassCastException - 如果指定元素的类型与此 collection 不兼容(可选)。
NullPointerException - 如果指定的元素为 null,并且此 collection 不支持 null 元素(可选)。
UnsupportedOperationException - 此 collection 不支持 remove 操作。
而且euqals和hashCode的定义必须一致.
由于程序里决定equals的是name和age
而hashCode里面只用了name的hashCode
所以个人认为这不是一个好的hashCode方法.
public class TestCollection {
public static void main(String[] args) {
Set c = new HashSet();
Worker wore = new Worker("royzhou","22");
c.add(wore);
System.out.println(c.size());
wore = new Worker("royzhou1","22");
c.add(wore);
System.out.println(c.size());
}
}class Worker {
String name;
String age;
Worker(String name, String age) {
this.name = name;
this.age = age;
}
public String toString() {
return name+" "+age;
}
public boolean equals(Object obj) {
return true;
}
public int hashCode() {
return name.hashCode();
}}Set的时候会调用hasCode,两个对像的name不一样(name是String类型,这个类型的HasCode方法已经实现好,会判断每个字符是否相同),所以add()两次会有两上对像,但当两上word对像都是同一个name的时候发现都是只有一个对像,就是说会调用hasCode方法比较,然后调用equals()方法去比较是否相同,如果都相同就不加了.