Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Array sizes of different types in java [duplicate]

Tags:

java

arrays

So I want to create a method that validates that two Arrays are of same length like:

validateSameSize(Object[] first, Object[] second) {
   if (first.length != second.length) throw new Exception();
}

The problem is that this method only works for non-primitive Arrays. If I want to compare a char-Array with another array this does not work. Is there a way to implement this function without too much overhead?

I have already tried

<T,V> validateSameSize(T[] first, V[] second)

but since generics also need a class and don't work with primitive types, this does not work. Also

validateSameSize(Array first, Array second)

doesn't work either

like image 634
Schottky Avatar asked Jan 26 '19 18:01

Schottky


2 Answers

You can use Array#getLength:

public static boolean sameSize(Object arrayA, Object arrayB) {
    return Array.getLength(arrayA) == Array.getLength(arrayB);
}

It will work with non-primitive arrays as well as with primitive ones:

System.out.println(sameSize(new int[0], new int[100])); // false
System.out.println(sameSize(new char[0], new int[0])); // true
System.out.println(sameSize(new Object[0], new Object[0])); // true
System.out.println(sameSize(new Object[0], new List[0])); // true

Also don't forget that passing an Object that is not an array to Array#getLength will result in IllegalArgumentException.

This code:

Object notArray = 100;
System.out.println(Array.getLength(notArray));

produces:

Exception in thread "main" java.lang.IllegalArgumentException: Argument is not an array

If you need to fail fast before invoking Array#getLength you can check if the argument is actually array:

if (!object.getClass().isArray()) {
  // object is not array. Do something with it
}
like image 50
Denis Zavedeev Avatar answered Oct 15 '22 23:10

Denis Zavedeev


The caco3 answer is fine.
Note that if the Object params are not arrays you will discover it only at runtime.
A safer way would be to overload the method for primitives :

void validateSameSize(Object[] first, Object[] second) throws Exception {
    if (first.length != second.length) throw new Exception();
}

void validateSameSize(int[] first, int[] second) throws Exception {
    if (first.length != second.length) throw new Exception();
}

And so for...
It will require you to write more code but your code would be more robust.

like image 30
davidxxx Avatar answered Oct 16 '22 01:10

davidxxx