在代码中的 "temparr.get(newindex) = arr.get(i);" 这一行获取错误//在将列表转换为数组时在这一行获取错误帮助
getting error at "temparr.get(newindex) = arr.get(i);" this line in code //getting error in this line as it converting list to array help for this
在“temparr.get(newindex) = arr.get(i);”处出现错误代码中的这一行//在将列表转换为数组时在这一行中出错帮助这个
class Result {
public static List<Integer> rotateLeft(int d, List<Integer> arr, int n) {
// Write your code here
List<Integer> temparr = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int newindex = ((i + (n - d)) % n);
// System.out.println(newindex);
temparr.get(newindex) = arr.get(i); //getting error in this line as it
converting list to array help for this
}
return temparr;
}
}
首先,您应该确保您使用的是正确的术语。您不是将 List
转换为数组,而是转换为 ArrayList
。一个 ArrayList
被称为那个,因为它像数组一样具有随机访问(实际上在内部使用数组),但它不是数组。
您的代码有两个问题:Java(实际上许多编程语言)不允许您在 assignment statement (=
).
我猜你想将 arr.get(i)
的值分配给 temparr
(*) 的索引 newindex
,所以你需要使用 .set()
方法:
temparr.set(newindex, arr.get(i));
但是这也行不通。您创建的 ArrayList
的大小为 0,因此不能将值分配给大于 0 的索引。您使用列表的方式需要使用 n
值(例如,0
或 null
)。例如,可以使用 Collections.nCopies()
:
List<Integer> temparr = new ArrayList<Integer>(Collections.nCopies(n, 0));
(*) 注意:“temparr
”是一个错误的变量名。它不是数组,所有变量都是“临时”的。使用明确描述内容或目的的名称。在这种情况下,我建议 rotatedList
.
在“temparr.get(newindex) = arr.get(i);”处出现错误代码中的这一行//在将列表转换为数组时在这一行中出错帮助这个
class Result {
public static List<Integer> rotateLeft(int d, List<Integer> arr, int n) {
// Write your code here
List<Integer> temparr = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int newindex = ((i + (n - d)) % n);
// System.out.println(newindex);
temparr.get(newindex) = arr.get(i); //getting error in this line as it
converting list to array help for this
}
return temparr;
}
}
首先,您应该确保您使用的是正确的术语。您不是将 List
转换为数组,而是转换为 ArrayList
。一个 ArrayList
被称为那个,因为它像数组一样具有随机访问(实际上在内部使用数组),但它不是数组。
您的代码有两个问题:Java(实际上许多编程语言)不允许您在 assignment statement (=
).
我猜你想将 arr.get(i)
的值分配给 temparr
(*) 的索引 newindex
,所以你需要使用 .set()
方法:
temparr.set(newindex, arr.get(i));
但是这也行不通。您创建的 ArrayList
的大小为 0,因此不能将值分配给大于 0 的索引。您使用列表的方式需要使用 n
值(例如,0
或 null
)。例如,可以使用 Collections.nCopies()
:
List<Integer> temparr = new ArrayList<Integer>(Collections.nCopies(n, 0));
(*) 注意:“temparr
”是一个错误的变量名。它不是数组,所有变量都是“临时”的。使用明确描述内容或目的的名称。在这种情况下,我建议 rotatedList
.