Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to pass a generic Array as parameter

Tags:

java

My question is quite simple:

I have the following method in my generic class (with type parameters A and B)

public void add(A elem, int pos, B[] assoc)

What I want to do is create a method

public void add(A elem, int pos)

which calls the upper method with a empty Array in assoc. So far I havnt found a solution, since Java doesnt allows to instantiate arrays of generic types.

like image 540
Jakob Abfalter Avatar asked Nov 25 '13 20:11

Jakob Abfalter


3 Answers

Java generic method which accepts a generic array.

public <T> void printArray(T[] array){
        for (T element: array){
            System.out.println(element);
        }
    }

The method which accepts generic list.

public <T> void printList(List<T> list){
      for (T element : list){
           System.out.println(element);
      }
}
like image 102
Lokesh Singal Avatar answered Oct 23 '22 09:10

Lokesh Singal


For two generic class AClass<T> and BClass<T> i can think of one way: Taking the advantage of varargs and using two different named function add() and addA():

public static <T>void addA(AClass<T> elem, int pos, BClass<T>... assoc){}

public static <T>void add(AClass<T> elem, int pos)
{
   addA(elem, pos);
}
like image 43
Sage Avatar answered Oct 23 '22 10:10

Sage


As you said, Java doesn't support generic arrays creation, but thats probably because of how generic works, in short, generics matter only at compile time, after compilation all generic classes are just Object classes, so thats why you cant create generic array.

However, you can create an empty Object array and cast it:

class Generic<B> {
    public void add(A a, int pos, B[] assoc) {
        System.out.println("Length: " + assoc.length);
    }

    public void add(A a, int pos) {
        add(a, pos, (B[]) new Object[0]);
    }
}

when i call add without that array it prints 0 as expected.

like image 2
kajacx Avatar answered Oct 23 '22 09:10

kajacx