Java examples for Algorithm:List
add, remove and sort elements of an ArrayList
package arrays;/*from w w w. ja va 2s .com*/ import java.util.ArrayList; import java.util.Collections; public class ArrayListExample { public static void main(String[] args) { int maxElements = 5000; // Determines the maximum number of elements in // the ArrayList int randomNumber; // The random number to add to the ArrayList // This is how to declare an ArrayList of Integers ArrayList<Integer> listOfNumbers = new ArrayList<Integer>(); // Populate the ArrayList for (int loopCounter = 0; loopCounter < maxElements; loopCounter++) { randomNumber = (int) (Math.random() * 90000); listOfNumbers.add(randomNumber); } // Sort ArrayList Collections.sort(listOfNumbers); // Output the ArrayList, and removes the elements as they are printed for (int loopCounter = 0; loopCounter < listOfNumbers.size(); loopCounter++) { System.out.println(listOfNumbers.get(loopCounter)); listOfNumbers.remove(loopCounter); loopCounter--; // Used to keep the loopCounter at 0 } System.out.println(); } }