首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

重写equals跟hashCode方法,让入HashSet中的内容不重复

2012-10-12 
重写equals和hashCode方法,让入HashSet中的内容不重复?package com.zj.hashset.testimport java.util.Has

重写equals和hashCode方法,让入HashSet中的内容不重复

?

package com.zj.hashset.test;import java.util.HashSet;/** * 功能:重写equals和hashCode方法,让相同姓名的用户不能重复加入HashSet * @author zhengjiong * time:2011-9-14 下午11:52:44 */public class HashSet_Test {public static void main(String[] args) {People p1 = new People("zhangsan");People p2 = new People("zhangsan");System.out.println(p1.hashCode());System.out.println(p2.hashCode());HashSet set = new HashSet();set.add(p1);//HashSet会自动调用hashcode方法,List不会set.add(p2);System.out.println(set);}}class People {String name;public People(String name){this.name = name;}@Overridepublic int hashCode() {return this.name.hashCode();}@Overridepublic boolean equals(Object obj) {if(this == obj){return true;}if(obj != null){if(obj instanceof People){return this.name.equals(((People)obj).name) ? true : false;}}return false;}}

热点排行