Java: How to check if object is null?

前端 未结 9 1310
甜味超标
甜味超标 2021-01-30 08:11

I am creating an application which retrieves images from the web. In case the image cannot be retrieved another local image should be used.

While trying to execute the f

相关标签:
9条回答
  • 2021-01-30 08:46

    It's probably slightly more efficient to catch a NullPointerException. The above methods mean that the runtime is checking for null pointers twice.

    0 讨论(0)
  • 2021-01-30 08:48

    I use this approach:

    if (null == drawable) {
      //do stuff
    } else {
      //other things
    }
    

    This way I find improves the readability of the line - as I read quickly through a source file I can see it's a null check.

    With regards to why you can't call .equals() on an object which may be null; if the object reference you have (namely 'drawable') is in fact null, it doesn't point to an object on the heap. This means there's no object on the heap on which the call to equals() can succeed.

    Best of luck!

    0 讨论(0)
  • 2021-01-30 08:49

    Just to give some ideas to oracle Java source developer :-)

    The solution already exists in .Net and is more very more readable !

    In Visual Basic .Net

    Drawable drawable 
        = If(Common.getDrawableFromUrl(this, product.getMapPath())
            ,getRandomDrawable()
            )
    

    In C#

    Drawable drawable 
        = Common.getDrawableFromUrl(this, product.getMapPath() 
            ?? getRandomDrawable();
    

    These solutions are powerful as Optional Java solution (default string is only evaluated if original value is null) without using lambda expression, just in adding a new operator.

    Just to see quickly the difference with Java solution, I have added the 2 Java solutions

    Using Optional in Java

    Drawable drawable = 
        Optional.ofNullable(Common.getDrawableFromUrl(this, product.getMapPath()))
            .orElseGet(() -> getRandomDrawable());
    

    Using { } in Java

    Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
    if (drawable != null)
        {
        drawable = getRandomDrawable();
        }
    

    Personally, I like VB.Net but I prefer ?? C# or if {} solution in Java ... and you ?

    0 讨论(0)
提交回复
热议问题