1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
import java.util.*;
/**
* This class implements a reverse method for the <code>List</code>. This is
* a static method that invert the elements of the List.
*
* @version 1.6
*/
public class javaCollect {
/**
* Invert a list with recursion. Takes an element in the first list and puts
* it at the right place in the second.
*
* @param liste
* the list to invert
* @param result
* the (partial) inverted list
* @param level
* the recusrsion level (start with 1)
* @return the inverted list
*/
static List reverse(List liste, List result, int level) {
// test if the inversion is over
if (level <= liste.size()) {
// put the new element
result.add(liste.get(liste.size() - level));
// go with the next element
result = reverse(liste, result, level + 1);
}
return result;
}
/**
* Invert a list. This method don't modify the original list. Start the
* recursion.
*
* @param liste
* the list to invert
* @return the inverted list
*/
static List reverse(List liste) {
// create the new arrayfor the element
// if the List liste respect the contract of the Interface => there is
// no problem to put the List into an ArrayList.
List result = new ArrayList();
// invert the list
result = reverse(liste, result, 1);
return result;
}
/**
* A test routine for the class. Test with ArrayList, Vector, LinkedList. Do
* a inversion with the reverse method of the java API.
*
* @param args
* the argument from command line (empty)
*/
public static void main(String[] args) {
// ArrayList
List array = new ArrayList();
for (int i = 1; i <= 5; i++)
array.add("arrayItem" + i);
System.out.println(array);
List resultA = reverse(array);
System.out.println(resultA);
System.out.println("------------------------");
// Vector
List vector = new Vector();
for (int i = 1; i <= 5; i++)
vector.add("VectorItem" + i);
System.out.println(vector);
List resultV = reverse(vector);
System.out.println(resultV);
System.out.println("------------------------");
// LinkedList
List link = new LinkedList();
for (int i = 1; i <= 5; i++)
link.add("LinkItem" + i);
System.out.println(link);
List resultL = reverse(link);
System.out.println(resultL);
System.out.println("------------------------");
// inverse a vector with Collections.reverse();
List link2 = new LinkedList();
for (int i = 1; i <= 5; i++)
link2.add("Lwerweqtem" + i);
System.out.println(link2);
Collections.reverse(link2);
System.out.println(link2);
}
} |
Partager