user3396201
user3396201

Reputation:

ArrayList and java.lang.OutOfMemoryError

I am trying to make program that create an ArrayList of initial size of 1 and populate it with random numbers. Next, the ArrayList is cleared and the size of ArrayList is increased by 1 and again filled with random numbers. I want my program to repeat those steps until the ArrayList size will be equal to number specified by user.

So the output will be for example like:

1

3,8

6,3,7

...

n

I have produced so far:

public static void main (String args[]){
    
    ArrayList<Integer> al = new ArrayList<Integer>(); 
    Random rand = new Random();
    int val=1;
    int ii =1;
    while(val<400){
    for (int j = 0; j<ii;)
    {
        ii++;
        val++;
        pick = rand.nextInt(100);
        al.add(pick);
    }

    System.out.println("Contents of al: " + al);

    al.clear();
    System.out.print("Array has been cleared: " + al);
}

Any ideas how to make it work?

Upvotes: 0

Views: 55

Answers (2)

bhspencer
bhspencer

Reputation: 13560

You never increment j. You are incrementing ii and val inside the for loop where as I think you actually want to do it in the while loop. Try the example below.

    ArrayList<Integer> al = new ArrayList<Integer>(); 
    Random rand = new Random();
    int val=1;
    int ii =0;
    while(val < 400){
        for (int j = 0; j<ii; j++) {
            int pick = rand.nextInt(100);
            al.add(pick);
        }
        ii++;
        val++;
        System.out.println("Contents of al: " + al);
        al.clear();
        System.out.print("Array has been cleared: " + al);
    }

Your task would be much easier if you gave your variables meaningful names. e.g.

    ArrayList<Integer> al = new ArrayList<Integer>(); 
    Random rand = new Random();
    int lineNumber = 1;
    int lineLength = 0;
    while(lineNumber < 400){
        for (int randCount = 0; randCount < lineLength; randCount++) {
            int pick = rand.nextInt(100);
            al.add(pick);
        }
        lineLength++;
        lineNumber++;
        System.out.println("Contents of al: " + al);
        al.clear();
        System.out.print("Array has been cleared: " + al);
    }

Upvotes: 1

kraskevich
kraskevich

Reputation: 18556

for (int j = 0; j<ii;) {
    ii++;
    val++;
    pick = rand.nextInt(100);
    al.add(pick);
}

is an infinite loop(j is always 0 and ii is always positive). You should fix it(according to the desired semantics).

Upvotes: 0

Related Questions