- 论坛徽章:
- 0
|
equals hashcode 最好一起实现
用来remove一个对象 当属性作为索引时 使用hashCode()方法来调用
package self.collection.eg1;
import java.util.*;
class Name{
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Name(String name, int age) {
this.name = name;
this.age = age;
}
public boolean equals(Object obj) {
// TODO Auto-generated method stub
boolean rst=false;
if(obj instanceof Name){
rst=name.equals(getName())&&age==(getAge());
}
return rst;
}
public String toString() {
// TODO Auto-generated method stub
return "name"+name+"age"+age;
}
}
public class Test1 {
public static void main(String args[]){
Collection c=new HashSet(); //使用collection 的原因
c.add("hello");
c.add(new Name("s1",20));
c.add(new Integer(122)); //只能添加对象不能添加基础的数据类型 使用包装类
System.out.println(c.remove(new Name("s1",20)));
System.out.println(c);
System.out.println(c.size());
}
}
如上程序 不能够remove 指定的对象 在这种情况下我们需要添加hashcode ()方法
eg
package self.collection.eg1;
import java.util.*;
class Name{
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Name(String name, int age) {
this.name = name;
this.age = age;
}
public boolean equals(Object obj) {
// TODO Auto-generated method stub
boolean rst=false;
if(obj instanceof Name){
rst=name.equals(getName())&&age==(getAge());
}
return rst;
}
public String toString() {
// TODO Auto-generated method stub
return "name"+name+"age"+age;
}
public int hashCode() {
// TODO Auto-generated method stub
return name.hashCode()^new Integer(age).hashCode();
}
}
public class Test1 {
public static void main(String args[]){
Collection c=new HashSet(); //使用collection 的原因
c.add("hello");
c.add(new Name("s1",20));
c.add(new Integer(122)); //只能添加对象不能添加基础的数据类型 使用包装类
System.out.println(c.remove(new Name("s1",20)));
System.out.println(c);
System.out.println(c.size());
}
}
这是添加了hashCode 方法的例子
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/40487/showart_328041.html |
|