My program is as follows:
import java.util.*;
class evenNumber {
ArrayList<Integer> arrL=new ArrayList<Integer>();
ArrayList<Integer> saveEvenNumber(int N) {
if(N<2)
System.out.println("N should be greater than 2");
else
for(int i=1;i<N;i++)
{
while(i%2==0)
{
arrL.add(i);
}
}
return arrL;
}
void printEvenNumber() {
Iterator<Integer> tr=arrL.iterator();
while(tr.hasNext())
{
System.out.print(tr.next());
System.out.print("*2, ");
}
}
}
public class First {
public static void main(String args[]) {
evenNumber eN=new evenNumber();
eN.saveEvenNumber(13);
eN.printEvenNumber();
}
}
I am getting the following error:
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.grow(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at list.evenNumber.saveEvenNumber(First.java:15)
at list.First.main(First.java:35)`
I have changed the size in Run > Run configuration > Arguments as mentioned in other posts on the same error but then also I am getting the same error.
What should I do?
while(i%2==0) { arrL.add(i); }. Independent of your memory settings, this will run out of memory sooner or later.if(i%2==0)instead.printEvenNumberis one way to do it, but a simpleforloop would be more readable:for (Integer i : arrL) { System.out.print(i); System.out.print("*2, "); }would do the same.