Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove values in ArrayList at indexes specified in int[]

The method takes an array of ints which are the indexes, and an ArrayList<String>. Items in the ArrayList with the index of the values in the index array are to be removed from the list.

When I run the following code, no items are removed. Can anyone explain what I’m doing wrong here?

  public static ArrayList<String> removeItems (ArrayList<String> list, int[]indexes){
         
         TreeSet<Integer> set = new TreeSet<>();
         
         for(Integer i : indexes) {
             set.add(i);
         }
         
        for(Integer i : set) {
            list.remove(i);
            i--;
        }
         
         return list;
     }

main method:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public static void main(String[] args) {
        
        ArrayList<String>list = new ArrayList<>();
        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");
        
    int[] arr = {2,3};

    ArrayList<String> newList = removeItems(list, arr);
    
    System.out.println(newList.toString());
    

}

>Solution :

There are 2 remove methods available for Lists, which seem somewhat identical, but do very different things:

As you can see the 2nd method takes in an Object. Integer is an instance of Object. int on the other hand, is a primitive type. To be able to solve your problem you need to make sure you pass int to remove() instead of Integer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading