difference between null != something and something != null

前端 未结 7 1672
庸人自扰
庸人自扰 2021-01-22 11:30

Is there a difference between null != something and something != null in Java. And if there is a difference then which one should I use and why??

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-22 12:11

    I just want to point out that the "Yoda condition" rationale for doing this (in languages like C & C++) does not apply in this (Java) case.

    1. Java does not allow general expressions to be used as statements, so both

       something == null;
      

      and

       null == something;
      

      would be compilation errors.

    2. The types of something == null and something = null are different; boolean and some reference type respectively. In this case, it means that both:

       if (something = null) {
           ...
       }
      

      and

       if (null = something) {
           ...
       }
      

      would be compilation errors.

    In fact, I can't think of a realistic example where null == something would be compilation error and something == null would not. Hence, it doesn't achieve anything in terms of mistake-proofing.

提交回复
热议问题