Compare two objects in Java with possible null values

前端 未结 12 1534
忘掉有多难
忘掉有多难 2020-11-27 11:58

I want to compare two strings for equality when either or both can be null.

So, I can\'t simply call .equals() as it can contain null<

12条回答
  •  甜味超标
    2020-11-27 12:41

    Since Java 7 you can use the static method java.util.Objects.equals(Object, Object) to perform equals checks on two objects without caring about them being null.

    If both objects are null it will return true, if one is null and another isn't it will return false. Otherwise it will return the result of calling equals on the first object with the second as argument.

提交回复
热议问题