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:
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:
- remove at an index:
E remove(int index) - remove an element from the list:
boolean remove(Object o)
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.