我试图执行下面的代码。它运行时没有任何编译错误。但 remove(int index)
方法未按预期工作。
import java.util.*;
public class Stones {
static int findLastStoneWeight(ArrayList<Integer> weight)
{
while(true)
{
Collections.sort(weight);
int n=weight.size();
if (n==1)
return weight.get(0);
else if(weight.get(n-1)>weight.get(n-2))
{
int temp1=weight.get(n-1);
int temp2=weight.get(n-2);
weight.add(n-2,temp1-temp2);
weight.remove(n-1);
System.out.println(weight.size()); //The new size of weight should be decreased by 1 but it does not!!
}
else
{
weight.remove(n-1);
weight.remove(n-2);
}
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<Integer> weight=new ArrayList<Integer>();
System.out.println("Enter the weights:");
while(true)
{
int w=sc.nextInt();
if(w<0)
break;
weight.add(w);
}
int lswt=findLastStoneWeight(weight);
System.out.println("Last stone weight:"+lswt);
}
}
当我对ArrayList权重
使用remove(int index)
方法时,ArrayList
的大小应该减少1,但它保持不变。为什么?
最佳答案
在您注意到的 else if
分支中,首先将一个元素添加到 weight
ArrayList:
weight.add(n-2,temp1-temp2);
然后删除一个元素:
weight.remove(n-1);
总而言之,您添加了一个元素并删除了一个元素,因此方法末尾的列表大小将与方法开始时的列表大小相同。
关于java - 为什么 java.util.ArrayList.remove(int index) 对于以下代码无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56924073/