本帖最后由 周之浩 于 2013-7-19 08:23 编辑
hashSet中不能存放两个用equals(重写父类Object类的equals(Object obj))比较相等的值,如果两个对象用equals比较为true则只能放入一个对象,后放入的对象被丢掉而你的程序中没有用equals方法比较相同的两个对象,可以看看我写的小例子如果不懂我再给你讲讲- package com.ccit;
- import java.util.Collection;
- import java.util.HashSet;
- public class HashTest {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Collection<People> coll = new HashSet<People>();
- People p1 = new People("zhou", 22, "男");
- People p2 = new People("zhan", 25, "女");
- People p3 = new People("lisi", 26, "男");
- People p5 = new People("zhou", 28, "女");
- People p4 = new People("zhou", 22, "男");
- coll.add(p1);
- coll.add(p2);
- coll.add(p3);
- coll.add(p4);
- coll.add(p5);
- System.out.println(coll.size());
- for(People p : coll)
- {
- System.out.println(p);
- }
- }
- }
- class People
- {
- private String name;
- private int age;
- private String sex;
-
- public People(String name,int age,String sex)
- {
- this.name = name;
- this.age = age;
- this.sex = sex;
- }
- @Override
- public boolean equals(Object obj) {
- boolean flag = false;
- if(obj instanceof People)
- {
- People p1 = (People)obj;
- if(this.hashCode() == p1.hashCode())
- flag = true;
- }
- return flag;
- }
- @Override
- public int hashCode() {
- return name.hashCode()+sex.hashCode()+age;
- }
- @Override
- public String toString() {
- // TODO Auto-generated method stub
- return this.name+"\t"+this.age+"\t"+this.sex;
- }
-
-
- }
复制代码 |