KaiquanMah's picture
Create 10. Array from list
3bf0ae7 verified
raw
history blame
2.2 kB
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]