Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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)

like image 484
jcvandam Avatar asked Oct 19 '25 15:10

jcvandam


1 Answers

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++)
like image 176
M A Avatar answered Oct 21 '25 05:10

M A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!