Java 错误需要意外类型:变量;找到:ArrayList 中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25693981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Error unexpected type required: variable; found: value in an ArrayList
提问by jcvandam
I am trying to allocate a random ArrayList array with size elements, fill with random values between 0 and 100
我正在尝试分配一个具有大小元素的随机 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) 处抛出错误
回答by M Anouti
Replace
代替
rval.get(i) = rand.nextInt(100);
with
和
rval.add(rand.nextInt(100));
Also the forloop will iterate zero times when rval.size()is used because the list is initially empty. It should use the parameter sizeinstead. 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循环将在rval.size()使用时迭代零次,因为列表最初是空的。它应该改用参数size。当您使用 初始化列表时new ArrayList<Integer>(size),您只是在设置其初始容量。那个时候名单还是空的。
for (int i = 0; i < size; i++)

