I was playing with some examples of Collections from Oracle website
public class Timing {
public static void method(){
List numbers = new ArrayList();
for (double i = 1; i <= Double.MAX_VALUE; i++)
numbers.add(new Double(i));
Collections.shuffle(numbers);
List winningcombination = numbers.subList(0, 10);
Collections.sort(winningcombination);
}
public static void main(String[] args)
{
long start = System.currentTimeMillis();
method();
long end = System.currentTimeMillis();
System.out.println("time elapsed : " + (end-start));
}
}
I tried to see how long it will take to do it for Double.MAX_VALUE. And I got this :
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.ensureCapacity(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
I there a way to fix this ?
Increasing the size of the heap will do. Just run the program with this argument:
It will increase your heap size to 512 MB. You can specify as much as you want: 1g, 2g and so on.
Even if you had enough memory,
ArrayList
can have at mostInteger.MAX_VALUE
elements.Double.MAX_VALUE
far exceeds said limit.In this case, you ran out of memory during an
add
that caused the array list to grow.Is there a way to allow you to create and store
Double.MAX_VALUE
objects in aCollection
? No. There's not that much RAM on Earth.Double.MAX_VALUE
is about 2 times ten to the 308th power: that's 2 followed by over 300 zeros. Give Best Buy a call, see how much they'd charge to put that in your computer.Yet another reason why your code cannot work:
double
can only represent integers exactly up to about 2^52 - after that,i++
will have no effect and thefor
loop will never terminate.You should never use floating-point variables as loop counters. Use
int
orlong
instead.Instead of doing what you are currently doing, you should just obtain 10 random doubles, add them to an ArrayList and sort it. That is basically what your method is doing.
To obtain a random double, look at
Random.nextDouble()
.You are trying to allocate of the order of 10^308 values. That's a lot of values.