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条回答
Juvenile、少年°
2楼-- · 2019-08-04 11:51

Increasing the size of the heap will do. Just run the program with this argument:

-Xmx512m

It will increase your heap size to 512 MB. You can specify as much as you want: 1g, 2g and so on.

查看更多
forever°为你锁心
3楼-- · 2019-08-04 11:55

Even if you had enough memory, ArrayList can have at most Integer.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.

查看更多
Root(大扎)
4楼-- · 2019-08-04 12:01

Is there a way to allow you to create and store Double.MAX_VALUE objects in a Collection? 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.

查看更多
劳资没心,怎么记你
5楼-- · 2019-08-04 12:01

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 the for loop will never terminate.

You should never use floating-point variables as loop counters. Use int or long instead.

查看更多
我命由我不由天
6楼-- · 2019-08-04 12:05

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().

查看更多
叛逆
7楼-- · 2019-08-04 12:08

You are trying to allocate of the order of 10^308 values. That's a lot of values.

查看更多
登录 后发表回答