简体   繁体   English

所需的Java错误意外类型:变量; 找到:ArrayList中的值

[英]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 我正在尝试分配一个具有size元素的随机ArrayList数组,并填充0到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 我已经尝试过.set和.get方法,但是它们似乎都不起作用

I keep getting the error unexpected type required: variable; 我不断收到所需的错误意外类型:变量; found: value 找到:价值

It is throwing the error at .get(i) 它在.get(i)处抛出错误

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. 同样,使用rval.size()时, for循环将迭代0次,因为该列表最初为空。 It should use the parameter size instead. 它应该改为使用参数size When you initialize the list using new ArrayList<Integer>(size) , you are only setting its initial capacity . 使用new ArrayList<Integer>(size)初始化列表时,仅设置其初始容量 The list is still empty at that moment. 该列表当时仍为空。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM