为什么我不能将 ArrayList 大小保存为变量?
public static ArrayList <Integer > merge(ArrayList <Integer > list1,
ArrayList <Integer > list2 ) {
if (list1.size() >= list2.size()) {
int maxSize = list1.size();
} else {
int maxSize = list2.size();
}
for (int i = 0; i < maxSize; i++) {
if (i <= list2.size()) {
int nextInList2 = list2.get(i);
list1.add(i, nextInList2);
}
}
System.out.println(list1);
return (list1);
Run Code Online (Sandbox Code Playgroud)
in: int maxSize = list1.size(); 我认为它没有按照我想要的方式保存变量。
我假设
list1.size()
Run Code Online (Sandbox Code Playgroud)
是一个整数
只需在 if 和 else 语句上方声明 maxSize 即可。鲍勃是你叔叔。然后您可以在方法/函数中的任何地方使用 maxSize。
这是一个范围问题。要解决您的问题,请在 if-else 语句的括号外声明变量 (maxSize)。当您在括号中声明它们时,您将只能在其中(范围)内使用它们。
int maxSize = 0;
if (list1.size() >= list2.size()) {
maxSize = list1.size();
} else {
maxSize = list2.size();
}
// Now maxSize can be used as you wish :)
for (int i = 0; i < maxSize; i++) { ...
Run Code Online (Sandbox Code Playgroud)
笔记:
int maxSize = Math.max(list1.size(), list2.size());
范围定义了变量的生命周期。让我们更深入地看看你的例子。为了简单起见,让我们忽略 else。
...
if (list1.size() >= list2.size()) {
// Start If statement's Scope.
int maxSize = list1.size(); // Add maxSize to scope
// Max Size is in scope and can be used as you wish
// End the scope, in other words, maxSize does not exist anymore.
}
// maxSize has left the building, and the compiler does not know about it.
...
Run Code Online (Sandbox Code Playgroud)
这只是一个小例子。但您可以在这里或这里找到更多(更好)的信息
希望这可以帮助