When overriding equals
method for an object can obj
below ever be null
, if so what are the circumstances?
@Override
public boolean equals(Object obj) {
Yes, equals()
should handle null
and in that case it should return false
as documented in Object.equals()
:
For any non-null reference value
x
,x.equals(null)
should returnfalse
.
Of course if x
is null
x.equals(null)
won't return true
but it will throw NullPointerException
. If you need to compare two possibly null
references look at Objects.equals(Object, Object)
:
Objects.equals(x, x);
The above is always true
, even if x == null
.
It's a public method. It can be null whenever a caller passes a null value into it. You have to handle that case appropriately.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.