Code Example
 

 

The following codeblock defines an ArrayList containing five robots, each named Johnny-x where x is a number 1-5. A newest robot is then defined as the last robot in the list using the size() method, and printed out. The list is then sorted in reverse order using a Comparator object that's been defined using the reverseOrder() method from the Collections class. An Iterator is then used to print out every element, which will now be in reverse order.

import java.util.*;

public class ArrayListExample {
      public ArrayListExample() {
            ArrayList theList = new ArrayList();
            for (int i = 1; i <= 5; i++)
                  theList.add(new String("Johnny-" + i));
            int numRobots = theList.size();
            String newestRobot = theList.get(numRobots-1).toString();
            System.out.println(newestRobot);

            Comparator comp = Collections.reverseOrder();
            Collections.sort(theList, comp);
            Iterator iter = theList.iterator();
            while(iter.hasNext()) {
                  System.out.println(iter.next());
            }
      }

      public static void main(String[] args) {
            ArrayListExample ale = new ArrayListExample();
      }
}

 



<< First | < Previous Next > | Last >>