问题
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 ?
回答1:
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.
回答2:
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.
回答3:
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.
回答4:
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().
回答5:
You are trying to allocate of the order of 10^308 values. That's a lot of values.
回答6:
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.
回答7:
for (double i = 1; i <= Integer.MAX_VALUE; i++)
numbers.add(new Double(i));
回答8:
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.
来源:https://stackoverflow.com/questions/7013384/java-lang-outofmemoryerror-java-heap-space