// demonstrates ArrayList type with a sort method (similar to problem 11.11 on page 447) import java.util.*; // ArrayList and Scanner public class ArrayListUser { public static void main(String[] args) { ArrayList list = new ArrayList(); // create an empty ArrayList of Integer types Scanner in = new Scanner(System.in); System.out.print("Enter int values ending with any negative "); // get int values and fill the ArrayList, boxing each int as an Integer int temp = in.nextInt(); while(temp>=0) { list.add(new Integer(temp)); // add(Integer) without another parameter adds the Integer at the end of the list System.out.print("Enter next int value ending with any negative "); temp = in.nextInt(); } sort(list); // call the sort method for(Integer i: list) // iterator for loop to iterate through each Integer in the ArrayList System.out.print(i.intValue()+"\t"); // unbox the Integer and print it out System.out.println("\n\n"); } // implementation of bubble sort for ArrayList (note: not quite as efficient since we are not decrementing size each time through the outer while loop) public static void sort(ArrayList list) { boolean done = false; // assume we are not done sorting yet int i1, i2, temp, i; // i1 and i2 will store the two Integer values being compared, used for unboxing while(!done) { done = true; // assume our last time through for(i=0;ii2) // compare them to see if we need to swap { temp=i1; list.set(i, new Integer(i2)); // instead of direct assignment, we use the set method, setting the item at index i to the new Integer(i2) list.set(i+1, new Integer(temp)); // set the item at index i+1 to new Integer(temp (old i1)) done = false; // since we swapped, we aren't done sorting yet } } } } }