java - Properly removing an Integer from a List<Integer> -


here's nice pitfall encountered. consider list of integers:

list<integer> list = new arraylist<integer>(); list.add(5); list.add(6); list.add(7); list.add(1); 

any educated guess on happens when execute list.remove(1)? list.remove(new integer(1))? can cause nasty bugs.

what proper way differentiate between remove(int index), removes element given index , remove(object o), removes element reference, when dealing lists of integers?


the main point consider here 1 @nikita mentioned - exact parameter matching takes precedence on auto-boxing.

java calls method best suits argument. auto boxing , implicit upcasting performed if there's no method can called without casting / auto boxing.

the list interface specifies 2 remove methods (please note naming of arguments):

  • remove(object o)
  • remove(int index)

that means list.remove(1) removes object @ position 1 , remove(new integer(1)) removes first occurrence of specified element list.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -