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