KaiquanMah/TurkuBasicOOPinJava
0
1Write the method2 3double[] newArray(ArrayList<Double> list)4 5which takes a list of floats as its parameter. 6The method creates and returns a floating point array with the same elements in the same order as the list.7 8Example method call:9 10public static void main(String[] args){11 ArrayList<Double> test = new ArrayList<>();12 test.add(1.0);13 test.add(3.0);14 test.add(2.75);15 16 double[] array = newArray(test);17 System.out.println("Array: " + Arrays.toString(array));18}19 20Program outputs:21Array: [1.0, 3.0, 2.75]22 23 24 25================26 27 28import java.util.Random;29import java.util.ArrayList;30import java.util.Arrays;31 32public class Test {33 public static void main(String[] args) {34 final Random random = new Random();35 36 37 double[] decimalValues = {0, 0.25, 0.5, 0.75};38 39 for (int testNumber = 1; testNumber <= 3; testNumber++) {40 System.out.println("Test " + testNumber);41 ArrayList<Double> list = new ArrayList<>();42 int size = random.nextInt(5) + 5;43 for (int i = 0; i < size; i++) {44 double element = random.nextInt(10) + decimalValues[random.nextInt(decimalValues.length)];45 list.add(element);46 }47 48 System.out.println("List: " + list);49 double[] array = newArray(list);50 System.out.println("Array: " + Arrays.toString(array));51 System.out.println("");52 }53 }54 55 56 57 // CONVERT LIST TO ARRAY58 public static double[] newArray(ArrayList<Double> list) {59 double[] array = new double[list.size()];60 // for (int num: list) {61 // array[i] = num;62 // }63 64 // for list - need to get element using idx65 for (int i = 0; i < list.size(); i++) {66 array[i] = list.get(i);67 }68 return array;69 }70 71 72}73 74 75 76 77 78 79 80Test 181List: [3.0, 6.25, 5.0, 4.75, 1.25, 8.75, 0.0, 7.0, 0.0]82Array: [3.0, 6.25, 5.0, 4.75, 1.25, 8.75, 0.0, 7.0, 0.0]83 84Test 285List: [2.25, 9.75, 7.25, 2.25, 7.5, 5.25, 9.0, 8.75]86Array: [2.25, 9.75, 7.25, 2.25, 7.5, 5.25, 9.0, 8.75]87 88Test 389List: [4.5, 5.75, 9.5, 5.0, 9.75]90Array: [4.5, 5.75, 9.5, 5.0, 9.75]91 92 93 94 