在Java中输出集合Collection有四种方式,分别如下:
一)Iterator输出。 该方式适用于Collection的所有子类
public class Demo1{
public static void main(String[] args) throws Exception{
Set<Student> students=new HashSet<Student>();
students.add(new Person("Bill",25));
students.add(new Person("Jack", 32));
students.add(new Person("Lily", 33));
students.add(new Person("Mike",65));
students.add(new Person("Jeason",33));
Iterator<Student> item = studnets.iterator();
while(item.hasNext()){
System.out.println(item.next());
}
}
}
二)foreach输出。该方式适用于Collection的所有子类。
public class Demo2{
public static void main(String[] args) throws Exception{
Set<Student> students=new HashSet<Student>();
students.add(new Person("Bill",25));
students.add(new Person("Jack", 32));
students.add(new Person("Lily", 33));
students.add(new Person("Mike",65));
students.add(new Person("Jeason",33));
for(Student item:students){
System.out.println(item);
}
}
}
三)ListIterator。仅适用于List接口的子类。
public class Demo3{
public static void main(String[] args) throws Exception{
Set<Student> students=new HashSet<Student>();
students.add(new Person("Bill",25));
students.add(new Person("Jack", 32));
students.add(new Person("Lily", 33));
students.add(new Person("Mike",65));
students.add(new Person("Jeason",33));
ListIterator<Student> item = students.listIterator();
System.out.println("正序输出:");
while(item.hasNext()){
System.out.println(item.next());
}
System.out.println("反序输出:");
while(item.hasPrevious()){
System.out.println(item.previous());
}
}
}
四)Enumeration输出。仅适用于Vector类。
public class Demo4{
public static void main(String[] args) throws Exception{
Set<Student> students=new HashSet<Student>();
students.add(new Person("Bill",25));
students.add(new Person("Jack", 32));
students.add(new Person("Lily", 33));
students.add(new Person("Mike",65));
students.add(new Person("Jeason",33));
Enumeration<Student> item = students.elements();
while(item.hasMoreElements()){
System.out.println(item.nextElement());
}
}
}