What is Range.containsRange() in Java?
Overview
containsRange() is an instance method of the Range class that is used to check if the range contains all the elements of the range passed as a parameter.
How to import Range
We can find the definition of Range 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-langpackage, refer to the Maven Repository.
We can import the Range class as follows:
import org.apache.commons.lang3.Range;
Syntax
public boolean containsRange(final Range<T> otherRange)
Parameters
final Range<T> otherRange: TheRangeobject to check.
Return value
This method returns true if the Range object contains all the elements of the Range object passed as a parameter. Otherwise, it returns false.
Code
import org.apache.commons.lang3.Range;public class Main{public static void main(String[] args) {int fromValue = 100;int toValue = 400;Range<Integer> range1 = Range.between(fromValue, toValue);fromValue = 150;toValue = 200;Range<Integer> range2 = Range.between(fromValue, toValue);// Example 1System.out.printf("%s.containsRange(%s) = %s", range1, range2, range1.containsRange(range2));System.out.println();// Example 2fromValue = 300;toValue = 500;range2 = Range.between(fromValue, toValue);System.out.printf("%s.containsRange(%s) = %s", range2, range1, range2.containsRange(range1));System.out.println();}}
Explanation
Example 1
range1 = [100..400]range2 = [150..200]
The method returns true, which indicates that range1 contains all the elements of range2.
Example 2
range1 = [100..400]range2 = [300..500]
The method returns false, which indicates that range2 does not contain all the elements of range1.
Output
The output of the code will be as follows:
[100..400].containsRange([150..200]) = true
[300..500].containsRange([100..400]) = false