以相反的顺序打印任何集合中的项目? [英] Printing out items in any Collection in reverse order?

查看:233
本文介绍了以相反的顺序打印任何集合中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Java书籍的数据结构和问题解决中遇到以下问题:

I have the following problem in my Data Structures and Problem Solving using Java book:


例程,使用Collections API以相反的顺序打印任何集合中的项目。不要使用ListIterator。

Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator.

我不是把它放在这里,因为我想要有人做我的家庭作业, t似乎很清楚它要求我代码是什么!

I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code!

当它要求我写一个例程,是否在寻找一个单一的方法?我不太明白我如何使一个单一的方法工作的所有各种类型的集合(链表,队列,堆栈)。

When it asks me to write a 'routine', is it looking for a single method? I don't really understand how I can make a single method work for all of the various types of Collections (linked list, queue, stack).

如果任何人可以指导

推荐答案

无论这个问题不像一半的集合那么有意义没有固定排序(即TreeSet或PriorityQueue)的gstable顺序,您可以使用以下语句以反向自然顺序打印集合的内容:

Regardless from the question not making much sense as half of the collections have no gstable ordering of have fixed-ordering (i.e. TreeSet or PriorityQueue), you can use the following statement for printing the contents of a collection in reverse-natural order:

List temp = new ArrayList(src);
Collections.reverse(temp);
System.out.println(temp);



我实际上是创建一个数组列表,因为列表是唯一可以任意重新排序的结构。您将 src 集合传递到构造函数,该构造函数以集合自然顺序对 src 的内容进行初始化。然后将列表传递到 Collections.reverse()方法,该方法会颠倒列表,最后将其打印出来。

I essence you create an array list as lists are the only structure that can be arbitrarily reordered. You pass the src collection to the constructor which initializes the list withj the contents of the src in the collection natural order. Then you pass the list to the Collections.reverse() method which reverses the list and finally you print it.

这篇关于以相反的顺序打印任何集合中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆