Properly removing an Integer from a List

前端 未结 8 1805
面向向阳花
面向向阳花 2020-11-22 03:57

Here\'s a nice pitfall I just encountered. Consider a list of integers:

List list = new ArrayList();
list.add(5);
list.add(6);         


        
8条回答
  •  没有蜡笔的小新
    2020-11-22 04:59

    You can use casting

    list.remove((int) n);
    

    and

    list.remove((Integer) n);
    

    It doesn't matter if n is an int or Integer, the method will always call the one you expect.

    Using (Integer) n or Integer.valueOf(n) is more efficient than new Integer(n) as the first two can use the Integer cache, whereas the later will always create an object.

提交回复
热议问题