Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
arrayutils
communitycreator

What is ArrayUtils.isSameLength in Java?

abhilash

isSameLength is a static method of the ArrayUtils class that checks if two arrays are of the same length.

Properties of isSameLength

  • The two arrays can be of different types.

  • Passing null as one of the arguments is considered an array of length zero.

Add the Apache Commons Lang package

ArrayUtils is defined in the Apache Commons Lang package. To add Apache Commons Lang to the Maven Project, add 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.

How to import ArrayUtils

You can import the ArrayUtils class as follows.


import org.apache.commons.lang3.ArrayUtils;

Syntax


public static boolean isSameLength(final int[] array1, final int[] array2)

Parameters

  • final int[] array1: first array.

  • final int[] array2: second array.

Return value

The method returns true if the arrays are of the same length; otherwise, it returns false.

Code

Example 1

  • array1 = [1,2,3,4,5]
  • array2 = [19,23,32,31,43]

The isSameLength function will result in true, as the two arrays are of the same length.

Example 2

  • array1 = [1,2,3,4,5]
  • array2 = [true,false,true,false,true]

The isSameLength function will result in true. Although the arrays are of different types, the lengths of the arrays are equal.

Example 3

  • array1 = [1,2,3,4,5]
  • array2 = [19,23,32,31]

The isSameLength function will result in false, as the two arrays are of different lengths.

import org.apache.commons.lang3.ArrayUtils;

public class Main {

    public static void main(String[] args) {
        int[] array1 = {1,2,3,4,5};
        boolean[] array2 = {true, false,true, false, true};
        int[] array3 = {19,23,32,31};
        System.out.println("array1 and array2 are same length - " + ArrayUtils.isSameLength(array1, array2));
        System.out.println("array1 and array3 are same length - " + ArrayUtils.isSameLength(array1, array3));
    }
}

Output


array1 and array2 are same length - true
array1 and array3 are same length - false

RELATED TAGS

java
arrayutils
communitycreator
RELATED COURSES

View all Courses

Keep Exploring