Properly removing an Integer from a List

前端 未结 8 1803
面向向阳花
面向向阳花 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:46

    Note that even if the VM did not do the right thing, which it does, you could still ensure proper behaviour by using the fact that remove(java.lang.Object) operates on arbitrary objects:

    myList.remove(new Object() {
      @Override
      public boolean equals(Object other) {
        int k = ((Integer) other).intValue();
        return k == 1;
      }
    }
    

提交回复
热议问题