装箱拆箱陷阱记录

1 陷阱一

  • java
List<Short> list = new ArrayList<>();
list.add((short) 4);
boolean contains1 = list.contains(4); // false
boolean contains2 = list.contains((short)4); // true
  • 字节码
  Code:
       0: new           #2                  // class java/util/ArrayList
       3: dup
       4: invokespecial #3                  // Method java/util/ArrayList."<init>":()V
       7: astore_1
       8: aload_1
       9: iconst_4
      10: invokestatic  #4                  // Method java/lang/Short.valueOf:(S)Ljava/lang/Short;
      13: invokeinterface #5,  2            // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z
      18: pop
      19: aload_1
      20: iconst_4
      21: invokestatic  #6                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      24: invokeinterface #7,  2            // InterfaceMethod java/util/List.contains:(Ljava/lang/Object;)Z
      29: istore_2
      30: aload_1
      31: iconst_4
      32: invokestatic  #4                  // Method java/lang/Short.valueOf:(S)Ljava/lang/Short;
      35: invokeinterface #7,  2            // InterfaceMethod java/util/List.contains:(Ljava/lang/Object;)Z
      40: istore_3
      41: return
posted @ 2018-10-11 14:56  月下小魔王  阅读(196)  评论(0编辑  收藏  举报