I want to convert an array double[] to an immutable collection for use in a value object. However, I am dealing with a very large array and I keep getting the error java.lang.OutOfMemoryError: Java heap space.
I am currently using
Collections.unmodifiableList(DoubleStream.of(myArray).boxed().collect(Collectors.toList()));
I think it is because of this my program is running out of memory. Is there a cheaper way to convert double[] to an immutable list?
How about creating your own
List<Double>? If you implementAbstractList<Double>, you'd only need to implement two methods for an unmodifiable list:Usage:
Note that if you change the backing array, the list contents will change as well. To prevent this, you'd usually copy the array passed in, but since copying the array will probably cause an out of memory exception, I didn't do it.
Or if you use Guava, use
Doubles.asList(myBigDoubleArray), which does essentially the same thing. Thanks to Joe for the suggestion!