集合输出有四种方式:Iterator,ListIterator,foreach,Enumeration,
集合就用Iterator
public class test {
public static void main(String args[]) throws Exception {
Set<String> all = new HashSet<String>();
all.add("A");
all.add("B");
all.add("B");
Iterator<String> iter = all.iterator();
while(iter.hasNext()){
String str = iter.next();
System.out.println(str);
}
}
}
ListIterator专门为List定义的双向迭代
public class test {
public static void main(String args[]) throws Exception {
List<String> all = new ArrayList<>();
all.add("A");
all.add("B");
all.add("B");
ListIterator<String> iter = all.listIterator();
System.out.print("由前向后输出:");
while(iter.hasNext()){
String str = iter.next();
System.out.print(str + ',');
}
System.out.print("\n由后向前输出:");
while(iter.hasPrevious()){
System.out.print(iter.previous() + ',');
}
}
}
Enumeration适用于Vector
public boolean hasMoreElements(); //判断是否有下一个元素 等同于hasNext()
public E nextElement();//取出下一个元素 等同于next()
public class test {
public static void main(String args[]) throws Exception {
Vector<String> all = new Vector<>();
all.add("A");
all.add("B");
all.add("B");
Enumeration<String> iter = all.elements();
while(iter.hasMoreElements()){
System.out.println(iter.nextElement());
}
}
}
本文介绍了Java中集合的四种输出方式:Iterator、ListIterator、foreach 和 Enumeration,并通过具体示例展示了每种方式的特点及适用场景。
1125

被折叠的 条评论
为什么被折叠?



