Why java.util.ArrayList.remove(int index) is not working properly for the below code?

Pratip Chakraborty :

I was trying to execute the below code. It ran without any compilation errors. But the remove(int index) method is not working as expected.

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);
    }
}

When I used the remove(int index) method on the ArrayList weight the size of the ArrayList should get reduced by 1 but it remains the same. Why?

Mureinik :

in the else if branch you noted, you first add an element to the weight ArrayList:

weight.add(n-2,temp1-temp2);

and then remove an element:

weight.remove(n-1);

All in all, you've added an element and removed an element, so the size of the list at the end of the method will be same as it was in the metho'd begining.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=134066&siteId=1