Java ArrayList of Doubles

160,407

Solution 1

Try this:

List<Double> list = Arrays.asList(1.38, 2.56, 4.3);

which returns a fixed size list.

If you need an expandable list, pass this result to the ArrayList constructor:

List<Double> list = new ArrayList<>(Arrays.asList(1.38, 2.56, 4.3));

Solution 2

ArrayList list = new ArrayList<Double>(1.38, 2.56, 4.3);

needs to be changed to:

List<Double> list = new ArrayList<Double>();
list.add(1.38);
list.add(2.56);
list.add(4.3);

Solution 3

Try this,

ArrayList<Double> numb= new ArrayList<Double>(Arrays.asList(1.38, 2.56, 4.3));

Solution 4

You are encountering a problem because you cannot construct the ArrayList and populate it at the same time. You either need to create it and then manually populate it as such:

ArrayList list = new ArrayList<Double>();
list.add(1.38);
...

Or, alternatively if it is more convenient for you, you can populate the ArrayList from a primitive array containing your values. For example:

Double[] array = {1.38, 2.56, 4.3};
ArrayList<Double> list = new ArrayList<Double>(Arrays.asList(array));

Solution 5

You can use Arrays.asList to get some list (not necessarily ArrayList) and then use addAll() to add it to an ArrayList:

new ArrayList<Double>().addAll(Arrays.asList(1.38L, 2.56L, 4.3L));

If you're using Java6 (or higher) you can also use the ArrayList constructor that takes another list:

new ArrayList<Double>(Arrays.asList(1.38L, 2.56L, 4.3L));
Share:
160,407
Robert Lu
Author by

Robert Lu

Updated on July 09, 2022

Comments

  • Robert Lu
    Robert Lu almost 2 years

    Is there a way to define an ArrayList with the double type? I tried both

    ArrayList list = new ArrayList<Double>(1.38, 2.56, 4.3);
    

    and

    ArrayList list = new ArrayList<double>(1.38, 2.56, 4.3);
    

    The first code showed that the constructor ArrayList<Double>(double, double, double) is undefined and the second code shows that dimensions are required after double.