你这样取没有问题的,但是取出来的不是你想要的,先看代码我说明
Student.java
- public class Student {
- private String name;
- private int age;
- private float score;
- public Student(String name, int age, float score) {
- this.name = name;
- this.age = age;
- this.score = score;
- }
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- public float getScore() {
- return score;
- }
- public void setName(String name) {
- this.name = name;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public void setScore(float score) {
- this.score = score;
- }
- }
复制代码
IteratorDemo.java
- import java.util.*;
- public class IteratorDemo {
- public static void main(String[] args) {
- Set<Student> set = new HashSet<Student>();
- set.add(new Student("Zhangsan", 20, 85f));
- set.add(new Student("Lisi", 22, 90f));
- set.add(new Student("Wangwu", 19, 87f));
- for (Iterator<Student> it = set.iterator(); it.hasNext(); ) {
- // Student student = it.next();
- // System.out.println(student.getName());
- System.out.println(it.next().getName() + " : " + it.next().getAge() + " : " + it.next().getScore());
- }
- }
- }
复制代码
我存入zhangsan , lisi, wangwu 后取出的顺序是wangwu,zhangsan,lisi
通过你的方式区的时候输出是:
getName() = wangwu
getAge() = 是zhangsan的年龄
getScore() = 是lisi的成绩
也就是说每一次it.next()的时候,都会取到下一个元素,这就是个问题了,最好通过我注释的方式。 |