Properly removing an Integer from a List

前端 未结 8 1686
面向向阳花
面向向阳花 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.

    0 讨论(0)
  • 2020-11-22 05:02

    Simply I did like following as suggested by #decitrig in accepted answer first comment.

    list.remove(Integer.valueOf(intereger_parameter));
    

    This helped me. Thanks again #decitrig for your comment. It may help for some one.

    0 讨论(0)
提交回复
热议问题