How to avoid null checking in Java?

后端 未结 30 3922
失恋的感觉
失恋的感觉 2020-11-21 04:43

I use object != null a lot to avoid NullPointerException.

Is there a good alternative to this?

For example I often use:



        
30条回答
  •  轮回少年
    2020-11-21 05:18

    Sometimes, you have methods that operate on its parameters that define a symmetric operation:

    a.f(b); <-> b.f(a);
    

    If you know b can never be null, you can just swap it. It is most useful for equals: Instead of foo.equals("bar"); better do "bar".equals(foo);.

提交回复
热议问题