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.
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);
}
}
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With