import java.util.*;
class Student{
private String name;
private int age;
public Student(String name,int age){
this.age = age ;
this.name = name ;
}
public String toString() {
return "name="+name+";age="+age;
}
}
public class HelloWorld{
public static void main(String[] args) {
HashSet<Student> hash = new HashSet<Student>();//實(shí)例化一個(gè)散列表---無(wú)固定順序
Student stu1 = new Student("789",14);
hash.add(new Student("123",12));
hash.add(new Student("456",13));
hash.add(stu1);
hash.add(new Student("012",15));
System.out.println("個(gè) 數(shù):"+hash.size());
System.out.println("------------foreach遍歷-----------");
for(Student a: hash) {
System.out.println(a);
}
hash.remove( stu1);//移除一個(gè)數(shù)據(jù)
//使用new Student("789",14)移除數(shù)據(jù)丛忆,失敗去团,但是使用stu1移除數(shù)據(jù)成功,為何沪羔?粉臊??
System.out.println("移除后個(gè)數(shù):"+hash.size());
System.out.println("------------for遍歷-----------");
Object[] object = hash.toArray(); //需要先將其轉(zhuǎn)換為數(shù)組斯稳,然后遍歷
for(int i = 0 ;i<hash.size();i++) {
System.out.println(object[i]);
}
System.out.println("------------Iterator遍歷-----------");
Iterator<Student> iterator = hash.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
System.out.println("-----------------------");
hash.clear();
System.out.println("清空后個(gè)數(shù):"+hash.size());
}
}
運(yùn)行結(jié)果
個(gè) 數(shù):4
------------foreach遍歷-----------
name=123;age=12
name=012;age=15
name=789;age=14
name=456;age=13
移除后個(gè)數(shù):3
------------for遍歷-----------
name=123;age=12
name=012;age=15
name=456;age=13
------------Iterator遍歷-----------
name=123;age=12
name=012;age=15
name=456;age=13
-----------------------
清空后個(gè)數(shù):0