In: Computer Science
This task has the following elements that are relevant to the learning outcomes of this module: - use ArrayList to save, find, insert items - convert from an array to an ArrayList - shuffle a list using your own method, sort a list You should write a simple Java class that will perform some operations on an ArrayList Create an Integer array of ten objects that you initialize with values 1 to 10. Convert it to an ArrayList object. Add a number Remove one of the numbers in the list. Ask the ArrayList object if it contains added value and the value that was removed. Create a method (do not use built-in shuffle methods) to put the values in a random order Arrange the array list in descending order and print it. Example of printing is:
Does list contain 42? Yes Does list contain 9? No 4 2 5 1 0 3 8 7 6 42 42 8 7 6 5 4 3 2 1 0
import java.util.ArrayList; import java.util.Comparator; import java.util.Random; public class Test { public static void main(String[] args) { //Create an Integer array of ten objects that you initialize with values 1 to 10. int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //Convert it to an ArrayList object. ArrayList<Integer> integers = new ArrayList<>(10); for (int num : numbers) { integers.add(num); } // Add a number; adding number 42 integers.add(42); //Remove one of the numbers in the list. Removing number 10 integers.remove(integers.indexOf(10)); //Ask the ArrayList object if it contains added value System.out.println("Does list contain 42? " + (integers.indexOf(42) >= 0 ? "Yes" : "No")); //and the value that was removed. System.out.println("Does list contain 10? " + (integers.indexOf(10) >= 0 ? "Yes" : "No")); shuffleArrayElements(integers); // printing after shuffling the array System.out.println("After shuffle:" + integers); //Arrange the array list in descending order and print it. integers.sort(new Comparator<Integer>() { @Override public int compare(Integer t2, Integer t1) { return t1-t2; } }); System.out.println("After sorting:" + integers); } //Create a method (do not use built-in shuffle methods) to put the values in a random order public static void shuffleArrayElements(ArrayList<Integer> integers) { Random random = new Random(); for (int i = 0; i < integers.size(); i++) { int randomNumber = random.nextInt(10); int temp = integers.get(i); integers.set(i, integers.get(randomNumber)); integers.set(randomNumber, temp); } } }
___________________________________________________________________________________________