Java: How to check if object is null?

前端 未结 9 1306
甜味超标
甜味超标 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条回答
  •  -上瘾入骨i
    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 ?

提交回复
热议问题