varargs with single and multi-dimentional arrays

Viewed 12

I have the following code in java working fine for var args and single dimensional arrays.

public class Main {
  public static void main(String[] args) throws ClassNotFoundException {
    MyConsumer<Integer> method1 = n -> n * n;
    Integer[] result1 = method1.run(10);
    for(Integer i : result1) {
        System.out.println(i);
    }
    
    MyConsumer<Integer> method3 = n -> n * n;
    Integer[] result3 = new Integer[]{10, 100};
    method3.run(result3);
    for(Integer i : result3) {
        System.out.println(i);
    }
  }
}
interface MyConsumer<T> {
    T execute(T args);
    default T[] run(T ...args) throws ClassNotFoundException {
        if (args.length > 0) {
            iterate(args);
            return args;
        }
        return null;
    }
    default void iterate(T ...obj) {
        for (int i = 0; i < obj.length; i++) {
            if (obj[i].getClass().isArray()) {
                iterate(obj[i]);
            } else {
                 obj[i] = execute(obj[i]);
            }
        }
    }
}

Now I want this to work for multidimensional arrays as well, like for the following:

MyConsumer<Integer> method5 = n -> n * n;
Integer[][] result5 = new Integer[][]{{10, 100}, {20}};
method5.run(result5);
for(Integer[] i : result5) {
    for (Integer j : i) {
        System.out.println(j);
    }
}

The above fails to compile with the following error

error: method run in interface MyConsumer cannot be applied to given types;

The code in the interface will work for var args and all dimensional arrays, but the problem here is to accept a multi dimensional array as varargs parameter we have to define the parameter type and return type with that no.of dimensions like for -

  • 2 dimensional parameter type is T[]... args and return type is T[][]
  • 3 dimensional parameter type is T[][]... args and return type is T[][][]

Can someone please suggest me the solution or other alternatives!! Solutions I thought are method overloading.

Thanks in advance!

0 Answers
Related