2015-10-24 89 views
-2
import java.util.Enumeration; 
import java.util.HashSet; 
import java.util.Iterator; 
import java.util.Vector; 

public class Test { 

    public static void main(String[] args) { 

     Employee e1 = new Employee("abc",10.0); 
     Employee e3 = new Employee("abc",10.0); 

     HashSet<Employee> hs = new HashSet<Employee>(); 
     hs.add(e1); 
     hs.add(e3); 

     System.out.println("size of hs : "+hs.size()); 

     Object [] aa = hs.toArray(); 

     for(int i=0;i<aa.length;i++){ 

      Object ii = aa[i]; 
      System.out.println("ii "+(i+1)+"="+ii.toString()); 
     } 

     Iterator it = hs.iterator(); 

     while(it.hasNext()){ 
      Employee e4 = (Employee) it.next(); 
      System.out.println("e4 ="+e4); 
      System.out.println("111="+it.next()); 
     } 

     Enumeration e5 = new Vector(hs).elements(); 
     while(e5.hasMoreElements()){ 
      Employee e6 = (Employee) e5.nextElement(); 
      System.out.println("e6 ="+e6); 
     } 

    } 

} 

public class Employee { 

    private String name; 
    private Double salary; 

    public Employee(String name, Double salary){ 
     this.name = name; 
     this.salary = salary; 
    } 

    public Employee(String name){ 
     this.name = name; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    public Double getSalary() { 
     return salary; 
    } 

    public void setSalary(Double salary) { 
     this.salary = salary; 
    } 

    @Override 
    public String toString() { 
     return "Employee [name=" + name + ", salary=" + salary + "]"; 
    } 

    public void getNameSal() throws NullPointerException{ 
     System.out.println(this.name +""+this.salary); 
    } 

} 

看着上面的代码,我创建了一个接受Employee类对象的散列集。 我创建了Employee类的两个对象,它们具有相同的值并添加到散列集中。 但是,当我打印大小的哈希集显示2. 而且当通过将其转换为数组,IteratorEnumerator三种方式进行迭代时,它会显示两个重复的值。 但是,当我尝试使用it.next()打印时,它只打印单个值。 这是为什么?为什么哈希集允许添加重复对象?

Output: 
size of hs : 2 
ii 1=Employee [name=abc, salary=10.0] 
ii 2=Employee [name=abc, salary=10.0] 
e4 =Employee [name=abc, salary=10.0] 
111=Employee [name=abc, salary=10.0] 
e6 =Employee [name=abc, salary=10.0] 
e6 =Employee [name=abc, salary=10.0] 
+7

问自己一个问题:如何知道两个员工是否平等?阅读Set的javadoc。 (和HashSet) –

+1

您不会覆盖雇员类中的equals和hashcode,并且您在调用iterator.next()两次时,一次是在初始化变量时,一次是在打印时。 –

回答

2

如果不实现equals()和hashCode()为你的Employee类,HashSet的使用默认等于实现,即一个对象只等于本身。因此,您的两个Employee对象不相等,因此第二个对象不会覆盖第一个对象。 因此,解决方案是在您的Employee类上实现equals()和hashCode(),并检查所有字段是否相等,这是您定义的两个Employees相等的一部分。

您只会看到一名员工打印,因为您的代码中存在一个错误:您在第一个while循环的每次迭代中都会调用next()两次。

+0

如果不谈论hashCode(),那么这个答案并不完整。 –

+0

你说得对,我回答得太快:) –

1

HashSet正在使用hashCodeequals方法的引擎盖后面的对象。

由于您没有为Employee类覆盖这些方法,因此HashSet只能看到两个员工在共享相同实例的情况下相同。

要解决您的问题,您需要在Employee类中覆盖hashCodeequals方法。

+1

** HashSet **使用hashCode和equals()。并非所有的Set实现都可以。 Set不使用任何东西:它是一个接口。 –

+0

你说得对,我编辑了我的修改。谢谢 – Maxime