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 ?
In you loop:
An
ArrayList
will just add the value to theArrayList
if there is room. If not it will increase the size of theArrayList
and then continue adding.So what you are basically doing is using all the memory allocated in your heap when you are creating this
ArrayList
. If you make yourArrayList
smaller you should be able to hold it in memory.