java.lang.OutOfMemoryError : Java heap space

2019-08-04 11:20发布

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 ?

8条回答
劳资没心,怎么记你
2楼-- · 2019-08-04 12:14
for (double i = 1; i <= Integer.MAX_VALUE; i++)
        numbers.add(new Double(i));
查看更多
beautiful°
3楼-- · 2019-08-04 12:15

In you loop:

for (double i = 1; i <= Double.MAX_VALUE; i++)
    numbers.add(new Double(i));

An ArrayList will just add the value to the ArrayList if there is room. If not it will increase the size of the ArrayList 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 your ArrayList smaller you should be able to hold it in memory.

查看更多
登录 后发表回答