jcvandam
jcvandam

Reputation: 57

Java Error unexpected type required: variable; found: value in an ArrayList

I am trying to allocate a random ArrayList array with size elements, fill with random values between 0 and 100

This is the block that I keep getting the error in

public static ArrayList<Integer> generateArrayList(int size)
{
    // Array to fill up with random integers
    ArrayList<Integer> rval = new ArrayList<Integer>(size);

    Random rand = new Random();

    for (int i=0; i<rval.size(); i++)
    {
        rval.get(i) = rand.nextInt(100);
    }

    return rval;
}

I've tried the .set and .get methods but neither of them seem to work

I keep getting the error unexpected type required: variable; found: value

It is throwing the error at .get(i)

Upvotes: 3

Views: 21222

Answers (1)

M A
M A

Reputation: 72844

Replace

rval.get(i) = rand.nextInt(100);

with

rval.add(rand.nextInt(100));

Also the for loop will iterate zero times when rval.size() is used because the list is initially empty. It should use the parameter size instead. When you initialize the list using new ArrayList<Integer>(size), you are only setting its initial capacity. The list is still empty at that moment.

for (int i = 0; i < size; i++)

Upvotes: 7

Related Questions