问:编写一个历程,使用集合类API以逆序打印出任何集合中的所有项,不能使用ListIterator
答:既然要求是任何集合,那就必须编写一个通用的方法,Collection可以泛指集合类,java中可以申明AnyType来予以实现。而要实现逆序,则可以通过栈Stack来达到目的,因为栈是先进后出,通过先将集合类的所有项压入栈,然后再出栈,则可以实现逆序。具体方法代码如下:
public static <AnyType> void printReverse(Collection<AnyType>c){
Iterator<AnyType> itr=c.iterator();
Stack<AnyType> sta=new Stack<AnyType>();
while(itr.hasNext()){
sta.push(itr.next());
}
while(!sta.empty()){
System.out.println(sta.peek());
sta.pop();
}
}
下面简单的进行测试1:
Collection<String> c=new ArrayList<String>();
c.add("jw");
c.add("and");
c.add("wxl");
printReverse(c);
输出为:
wxl
and
jw
测试2:
Collection<Integer> c1=new PriorityQueue<Integer>();
c1.add(4);
c1.add(3);
c1.add(5);
printReverse(c1);
输出为:
5
4
3
通过以上测试可以发现,完全符合要求,只要继承了Collection接口,集合内任意数据类型都可以。