Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two objects with a check for null

Is there a method in the JDK that compares two objects for equality, accounting for nulls? Something like this:

public static boolean equals(Object o1, Object o2) {     if (o1 == null)     {         return o2 == null; // Two nulls are considered equal     }     else if (o2 == null)     {         return false;     }      return o1.equals(o2); } 

It seems silly to write this method myself since I would think that it has to exist already somewhere.

like image 890
dcstraw Avatar asked Sep 09 '09 20:09

dcstraw


People also ask

How do you compare two null objects?

The compare() method in StringUtils class is a null-safe version of the compareTo() method of String class and handles null values by considering a null value less than a non-null value. Two null values are considered equal.

Can you use == for null?

equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null .

Can we compare two null values?

Using equals() method of the Object class In the same way the equals() method of the object class accepts two String values and returns a boolean value, which is true if both are equal (or, null) and false if not.

Can you do == null in Java?

7. == and != The comparison and not equal to operators are allowed with null in Java.


1 Answers

Java 7.0 added a new handy class: Objects.

It has a method exactly for this: Objects.equals(Object a, Object b)

like image 53
icza Avatar answered Oct 04 '22 12:10

icza