将一个整数数组列表与另一个整数数组列表相加,给出错误:预期变量 [英] Summing one ArrayList of Integers to another ArrayList of Integers, gives error: variable expected
问题描述
我的 Android 应用程序中有两个 6 个元素的 ArrayList.我们称它们为 ArrayListA"和B".我的类中的每个对象在构造函数中都有这一行:
I have two ArrayList of 6 elements in my Android application. Let's call them ArrayList "A" and "B". Each object in my class has this line in the constructor:
likes = new ArrayList<Integer>();
我也可以在构造函数中添加这一行(我不确定哪个更好,但我想将大小初始化为 6,并且所有元素都应为 0):
I could also add this line in the constructor (I'm not sure which one is better, but I want to initialize the size to 6, and all elements should be 0):
likes = new ArrayList<>(Collections.nCopies(6, 0));
我的类中有一个名为Calculate 的方法,该方法应该采用与A 大小相同的整数B 的新ArrayList 作为参数.然后将 B 与该对象的 ArrayList, A 相加/求和.
I have a method in my class called Calculate, which is supposed to take a new ArrayList of Integers, B, of the same size as A, as a parameter. Then add / sum B with this object's ArrayList, A.
方法如下:
public void Calculate(ArrayList<Integer> likes){
for(int i = 0; i < likes.size(); i++){
this.likes.get(i) += likes.get(i);
//this.likes.get(i) = 3;
}
}
我在 this.likes.get(i) 下方看到一条红线,说:
I'm getting a red line under the line this.likes.get(i), saying:
预期变量
即使我试着说 this.likes.get(i) = 3; 我也会得到同样的错误.
Even if I try to just say this.likes.get(i) = 3; I get the same error.
假设 A = {0,0,0,0,0,0},B = {1,0,0,-1,1,0}
Let's say A = {0,0,0,0,0,0}, and B = {1,0,0,-1,1,0}
对 ArrayList 求和以使 A = {1,0,0,-1,1,0} 的正确方法是什么?
What is the correct way to sum to ArrayList, to make A = {1,0,0,-1,1,0}?
推荐答案
您不能为 this.likes.get(i)
之类的值赋值.您只能为变量赋值.
You can't assign a value to a value such as this.likes.get(i)
.
You can only assign values to variables.
要修改 ArrayList
的 i
'th 元素,您应该使用 ArrayList
的 set
方法:
To modify the i
'th element of an ArrayList
you should use the ArrayList
's set
method:
this.likes.set(i,this.likes.get(i) + likes.get(i));
这篇关于将一个整数数组列表与另一个整数数组列表相加,给出错误:预期变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!