views:

1414

answers:

5

Okay, so 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.

A: 

Well you could have a routine that delegates to other routines based on the input type, however I'm not sure there is a generic enough collection type that can be encompassed into one argument. I guess you could just use method overloading (having multiple methods with the same name, but accept different args).

That could technically count as 1 routine (all have the same name).

Karan
+2  A: 

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

AdamC
thank you very much for the idea
outsyncof
no problem - good luck.
AdamC
A: 

Isn't there a base Collection class?

Probably worth looking here as a starting point...

http://java.sun.com/j2se/1.4.2/docs/api/java/util/Collections.html

Moishe
A: 

I don't know much Java, but considering the "Collections API" i imagine all those objects implement an interface you could iterate through someway. i suppose they all could have an itemAtIndex( int index ) and length() or similar method you could use.

You might want to read this.

Kris
+8  A: 

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.

ddimitrov
Collections.reverse returns void...
Tom Hawtin - tackline
oops... my bad - corrected the answer
ddimitrov