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

前端 未结 6 1450
广开言路
广开言路 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:23

    When you write

    foo.get(0)
    

    the compiler does not matter how you created the List. It only looks at the compile-time type of the List foo. So, if that is a List, it will treat that as a List, as it is supposed to do, and a List's get() always returns an Integer. If you want to use the == then you have to write

    System.out.println(foo.get(0).intValue() == bar.get(0).intValue());
    

    not

    System.out.println(foo.get(0) == bar.get(0));
    

    because that has a totally different meaning.

提交回复
热议问题