- package com.itcast.practise;
- import java.util.*;
- class PersonPractise{
- private String name;
- private int age;
- PersonPractise(String name,int age){
- this.name = name;
- this.age = age;
-
- }
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- public void setName(String name){
- this.name = name;
-
- }
- public void setAge(int age){
- this.age = age;
-
- }
- //如果把hashCode方法注释掉可以看出如果对象不同,hashCode就不一样,只比较了hashCode没调用equals方法
- //如果把hashCode方法不注释掉并且让它返回一个整数。那么PersonPractise的每个实例对象的hashCode都一样,
- //根据结果显示,使用HashSet的add方法时调用了equals方法。
- public int hashCode(){
- return 100;
-
- }
- public boolean equals(Object obj){
- PersonPractise p =(PersonPractise)obj;
- //打印是怎么比较的
- System.out.println(this.name +" equals "+p.name);
- int num = this.name.compareTo(p.name);
- if(num >0)
- return false;
- else if(num<0)
- return false;
- else if(this.age>p.age)
- return false;
- else if(this.age<p.age)
- return false;
- else return true;
-
- }
-
- }
- public class HashSetDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
-
- HashSet hs = new HashSet();
- PersonPractise lisi = new PersonPractise("lisi",25);
- PersonPractise aaa = new PersonPractise("aaa",21);
- PersonPractise zhangsan = new PersonPractise("zhangsan",25);
- hs.add(lisi);
- hs.add(aaa);
- hs.add(lisi);
- hs.add(zhangsan);
- //调用removeHashSet没有再次调用equals方法,说明调用add方法时就记录下了比较结果,lz只能看源码了。。。。
- hs.remove(zhangsan);
- sop(hs);
- }
- public static void sop(HashSet hs){
- Iterator it = hs.iterator();
- while(it.hasNext()){
- PersonPractise p =(PersonPractise)it.next();
- System.out.println(p.getName()+"-----"+p.getAge());
-
- }
-
-
- }
- }
复制代码 |