Reputation: 473
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
.
Upvotes: 19
Views: 206754
Reputation: 31
1) "Unnecessarily complicated" is IMHO to create first an unmodifiable List before adding its elements to the ArrayList.
2) The solution matches exact the question: "Is there a way to define an ArrayList with the double type?"
double type:
double[] arr = new double[] {1.38, 2.56, 4.3};
ArrayList:
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( new Supplier<ArrayList<Double>>() {
public ArrayList<Double> get() {
return( new ArrayList<Double>() );
}
} ) );
…and this creates the same compact and fast compilation as its Java 1.8 short-form:
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( ArrayList::new ) );
Upvotes: 3
Reputation: 1
double[] arr = new double[] {1.38, 2.56, 4.3};
ArrayList<Double> list = DoubleStream.of( arr ).boxed().collect(
Collectors.toCollection( new Supplier<ArrayList<Double>>() {
public ArrayList<Double> get() {
return( new ArrayList<Double>() );
}
} ) );
Upvotes: -1
Reputation: 30723
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));
Upvotes: 2
Reputation: 1193
Try this:
List<Double> l1= new ArrayList<Double>();
l1.add(1.38);
l1.add(2.56);
l1.add(4.3);
Upvotes: 2
Reputation: 424983
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));
Upvotes: 31
Reputation: 39436
Using guava
Doubles.asList(1.2, 5.6, 10.1);
or immutable list
ImmutableList.of(1.2, 5.6, 10.1);
Upvotes: 2
Reputation: 900
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));
Upvotes: 3
Reputation: 3078
Try this,
ArrayList<Double> numb= new ArrayList<Double>(Arrays.asList(1.38, 2.56, 4.3));
Upvotes: 4