Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing out items in any Collection in reverse order?

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

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

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).

If anybody could guide me in the right direction, I would greatly appreciate it.

like image 751
101010110101 Avatar asked Oct 13 '08 03:10

101010110101


2 Answers

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);

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.

like image 119
2 revs Avatar answered Nov 07 '22 15:11

2 revs


First, I believe it is asking you to write a method. Like:

void printReverseList(Collection col) {}

Then there are many ways to do this. For example, only using the Collection API, use the toArray method and use a for loop to print out all the items from the end. Make sense?

As for the various classes using the Collection interface, it will automatically work for all of those since they must implement the interface (provided they implement it in a sane way;).

like image 2
AdamC Avatar answered Nov 07 '22 13:11

AdamC