重写hashCode方法
2014-02-19 08:26
127 查看
//什么时候重修hashCode 方法? 当对象当作键值或者索引的时候 需要重写 import java.util.*; class Name{ private String name; private String age; public Name(String name,String age){ this.name=name; this.age=age; } public String toString(){ return this.name+" "+this.age; } public boolean equals(Object obj){ if(obj instanceof Name){ Name n=(Name)obj; return (name.equals(n.name)) && (age.equals(n.age)); }else return super.equals(obj); } public int hashCode(){ return name.hashCode(); } } public class Stu{ public static void main (String [] args) { Collection hash=new HashSet(); //添加元素 hash.add("hello"); hash.add(new Integer(200)); hash.add(new Name("majianjie","22")); //删除元素 hash.remove("hello"); hash.remove(new Integer(200)); System.out.println(hash.remove(new Name("majianjie","22"))); //在没有重写hashcode的方法时候,删除不了的,返回 false! System.out.println(hash); } }
相关文章推荐
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- 关于重写equals,hashcode以及compareTo方法
- 使用EqualsBuilder和HashCodeBuilder重写equals、hashCode方法
- String类重写equals()和hashCode()方法
- java中为什么重写equals时必须重写hashCode方法?
- 关于如何重写hashCode的方法
- Java中重写equals和hashCode方法的注意事项
- JAVA中重写自己的hashCode()方法原因
- 白菜之hashCode()方法重写及不同数据类型调用hashCode的方法
- 关于hibernate中实体中equals和hashcode方法的重写
- 关于equals与hashcode方法的重写原则
- JAVA中重写equals()方法为什么要重写hashcode()方法?
- 为什么要重写hashcode() 方法
- 重写equals方法和hashcode(集合需要重写)
- IDEA get/set/重写equals()、hashcode()\toString()等 方法快捷键
- equals 和 hashCode 的重写方法
- 为什么使用HashSet储存对象时必须重写equals和hashcode方法
- JAVA中重写equals()方法为什么要重写hashcode()方法说明
- 重写equals方法的同时为什么要重写hashcode方法
- 备忘:GetTypeHashCode() 没有找到适合的方法来重写