我试图执行以下代码。它没有任何汇编错误。但是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 weight
上使用remove(int index)
方法时,ArrayList
的大小应减少1,但保持相同。为什么?
在您注意到的else if
分支中,您首先将元素添加到weight
ArrayList:
weight.add(n-2,temp1-temp2);
然后删除一个元素:
weight.remove(n-1);
总的来说,您已经添加了一个元素并删除了一个元素,因此该方法末尾的列表的大小将与Metho的开始相同。