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>();//实例化一个散列表---无固定顺序
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("个 数:"+hash.size());
System.out.println("------------foreach遍历-----------");
for(Student a: hash) {
System.out.println(a);
}
hash.remove( stu1);//移除一个数据
//使用new Student("789",14)移除数据,失败,但是使用stu1移除数据成功,为何???
System.out.println("移除后个数:"+hash.size());
System.out.println("------------for遍历-----------");
Object[] object = hash.toArray(); //需要先将其转换为数组,然后遍历
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("清空后个数:"+hash.size());
}
}
运行结果
个 数:4
------------foreach遍历-----------
name=123;age=12
name=012;age=15
name=789;age=14
name=456;age=13
移除后个数: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
-----------------------
清空后个数:0
网友评论