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. 而且當通過將其轉換爲數組,Iterator
和Enumerator
三種方式進行迭代時,它會顯示兩個重複的值。 但是,當我嘗試使用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]
問自己一個問題:如何知道兩個員工是否平等?閱讀Set的javadoc。 (和HashSet) –
您不會覆蓋僱員類中的equals和hashcode,並且您在調用iterator.next()兩次時,一次是在初始化變量時,一次是在打印時。 –