rohan ghosh
rohan ghosh

Reputation: 177

Clarification of remove for Arraylist

So ArrayList in JAVA has 2 remove function 1 return the oldvalue and the other return boolean.

remove(Object) return boolean
remove(index) return oldvalue

now if both the object also integer then how JAVA differentiate

Ex:- in the code arr.remove(j);

Code

ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i = 2; i < 239697453; i++) {
    arr.add(i);
}
int a = arr.size();
for (int i = 2; i < a; i++) {
    for (int j = 0 j < a; j++) {
        if (arr.get(j) % i == 0) {
            arr.remove(j);
        }
    }
}

Upvotes: 2

Views: 397

Answers (1)

m.antkowicz
m.antkowicz

Reputation: 13571

Java firstly will choose the most suitable version of method - because

remove(int i)

is fitting better than

remove(Integer i) // autoboxing necessary

it will call the index version of remove method

To force Java to use item version you can create Integer object using Integer.valueOf() and pass it to the remove method

list.remove(Integer.valueOf(myInt))

See related page, What is the difference between Integer and int in Java?

Upvotes: 6

Related Questions