compare()
is a ObjectUtils
class that is used to compare two comparables.
Comparables are the objects whose classes implement the
Comparable
interface.
The method optionally accepts a parameter called nullGreater
. If true
, then null
is considered greater than a non null
value. If false
, then null
is considered less than a non null
value.
ObjectUtils
The definition of ObjectUtils
can be found in the Apache Commons Lang
package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-lang
package, refer to the Maven Repository.
You can import the ObjectUtils
class as follows:
import org.apache.commons.lang3.ObjectUtils;
public static <T extends Comparable<? super T>> int compare(final T c1, final T c2, final boolean nullGreater)
final T c1
: The first object.final T c2
: The second object.final boolean nullGreater
: A Boolean flag indicating if null
objects have to be treated as greater than or lesser than non null
objects.This method returns a positive value if c1 > c2
, a negative value if c1 < c2
, or zero if c1 = c2
.
import org.apache.commons.lang3.ObjectUtils;public class Main{public static void main(String[] args) {// Example 1String object1 = "hello";String object2 = "hello";System.out.printf("ObjectUtils.compare(%s, %s) = %s", object1, object2, ObjectUtils.compare(object1, object2));System.out.println();// Example 2object1 = "";object2 = "hello";System.out.printf("ObjectUtils.compare(%s, %s) = %s", object1, object2, ObjectUtils.compare(object1, object2));System.out.println();// Example 3object1 = "hello";object2 = null;System.out.printf("ObjectUtils.compare(%s, %s) = %s", object1, object2, ObjectUtils.compare(object1, object2));System.out.println();}}
The output of the code will be as follows:
ObjectUtils.compare(hello, hello) = 0
ObjectUtils.compare(, hello) = -5
ObjectUtils.compare(hello, null) = 1
object1 = "hello"
object2 = "hello"
The method returns 0
, as both the objects are equal.
object1 = ""
object2 = "hello"
The method returns -5
as object2
> object1
.
object1 = "hello"
object2 = null
The method returns 1
as object1
> object2
.