4

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)

2
  • On the right side of an = sign you need a value. On the left side you need a variable. A variable is (usually) a value, but not vice-versa. Commented Sep 5, 2014 at 21:12
  • See manouti's answer, but where you're going wrong in your thinking is in assuming that new ArrayList<Integer>(size) will create an ArrayList with size elements in it. It doesn't: it creates an empty list with capacity for size elements. (And in any case the capacity will grow as needed, so you don't usually have to worry about it.) Commented Sep 5, 2014 at 21:13

1 Answer 1

8

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++)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.