本帖最后由 张学东 于 2012-10-17 13:29 编辑
- package com.itheima.day14;
- import java.util.HashSet;
- import java.util.Iterator;
- public class HashSetTest {
- /**
- * 往hashSet集合中存入自定对像
- * 姓名和年龄相同为同一个人,重复元素。
- */
-
- public static void sop(Object obj){
- System.out.println(obj);
- }
- public static void main(String[] args) {
- HashSet hs=new HashSet();
-
- hs.add(new person("zhangsan",25));
- hs.add(new person("lisi",26));
- hs.add(new person("whangwu",27));
- hs.add(new person("zhangsan",25));
-
- Iterator it=hs.iterator();
- while(it.hasNext()){
- person p=(person)it.next();
- sop(p.getName()+p.getAge());
- }
- }
- }
- class person{
- private String name;
- private int age;
-
- person(String name, int age){
- this.name=name;
- this.age=age;
- }
- //重写object的equals方法
- public boolean equals(Object obj){
- if(!(obj instanceof person)){
- return false;
- }
- person p=(person)obj;
- System.out.println(this.name+"...equals.."+p.name);
- return this.name.equals(p.name)&& this.age==p.age ;
- }
- //重写hashcode方法
- public int hashCode()
- {
- System.out.println(this.name+"....hashCode");
- return name.hashCode()+age*37;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
-
-
-
- }
复制代码 谁能告诉我 在重新hashcode方法是 那个 age*37是什么意思啊 还有能给我解释这个hashCode吗?返回的hashCode怎么就是一样的呢?麻烦各位了...
|