Why can't the compiler/JVM just make autoboxing “just work”?

前端 未结 6 1293
广开言路
广开言路 2020-12-31 07:40

Autoboxing is rather scary. While I fully understand the difference between == and .equals I can\'t but help have the follow bug the hell out of m

6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 08:10

    If you skip autoboxing completely, you still get this behaviour.

    final List foo =
      Arrays.asList(Integer.valueOf( 1 ), Integer.valueOf( 1000 ));
    final List bar =
      Arrays.asList(Integer.valueOf( 1 ), Integer.valueOf( 1000 ));
    
    System.out.println(foo.get(0) == bar.get(0)); // true
    System.out.println(foo.get(1) == bar.get(1)); // false
    

    Be more explicit if you want a specific behavior:

    final List foo =
      Arrays.asList( new Integer( 1 ), new Integer( 1000 ));
    final List bar =
      Arrays.asList( new Integer( 1 ), new Integer( 1000 ));
    
    System.out.println(foo.get(0) == bar.get(0)); // false
    System.out.println(foo.get(1) == bar.get(1)); // false
    

    This is a reason, why Eclipse has autoboxing as a warning by default.

提交回复
热议问题