What is Range.equals() in Java?

Overview

The equals() method is an instance method of the Range class. It checks if two Range objects are equal. For the Range objects to be equal, the minimum and maximum values must be the same.

How to import range

The definition of Range 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 Range class as follows:


import org.apache.commons.lang3.Range;

Syntax


public boolean equals(final Object obj)

Parameters

final Object obj: The reference object with which to compare.

Return value

This method returns true if the objects are equal. Otherwise, it returns false .

Code

import org.apache.commons.lang3.Range;
public class Main{
public static void main(String[] args) {
// Example 1
int fromValue = 100;
int toValue = 200;
Range<Integer> range1 = Range.between(fromValue, toValue);
Range<Integer> range2 = Range.between(fromValue, toValue);
System.out.printf("(%s == %s) = %s", range1, range2, range1.equals(range2));
System.out.println();
// Example 2
toValue = 300;
range2 = Range.between(fromValue, toValue);
System.out.printf("(%s == %s) = %s", range1, range2, range1.equals(range2));
}
}

Output

The output of the code will be as follows:


([100..200] == [100..200]) = true
([100..200] == [100..300]) = false

Code explanation

Example 1

  • range1 = [100..200]
  • range2 = [100..200]

The method returns true as the minimum and maximum values of the objects are equal.

Example 2

  • range1 = [100..200]
  • range2 = [100..300]

The method returns false as the maximum values of the objects are not equal.

Free Resources