Comparing Array sizes of different types in java [duplicate]

  • A+

This question already has an answer here:

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


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)); 


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 } 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: