7

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.

Jakob Abfalter
  • 4,270
  • 14
  • 48
  • 81

3 Answers3

10

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);
      }
}
Dhiral Kaniya
  • 1,615
  • 1
  • 15
  • 29
Lokesh Singal
  • 133
  • 2
  • 8
  • Does this work? I get this error The method printArray(T[]) in the type MyClass is not applicable for the arguments (int[]) – Adam Mendoza Dec 17 '18 at 08:38
  • 1
    @AdamMendoza Template accepts only Object Type values, and you are trying to pass primitive data type (int), hence the error. – Lokesh Singal Dec 17 '18 at 19:09
  • 1
    However this works for both int and char public static void test(T result, T expect) {...}. It doesn't allow arrays of primitives but primitives by themselves are allowed. – Adam Mendoza Dec 17 '18 at 20:01
3

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);
}
Sage
  • 14,688
  • 3
  • 28
  • 34
  • well, varargs can be tricky and i would avoid it if possible. Consider following scenario: function `foo(Object... o) { ... }` is called with 1 argument which happens to be array of objects (like `foo(new Object[]{"asd", 45, '6', false}`) now what happens? Suprisingly, the array unwraps and `foo` recives 4 arguments! – kajacx Nov 25 '13 at 21:46
  • yes it can be tricky for the scenario you have given. But i don't think there is any other way with `generic class` keeping the type intact without varargs. – Sage Nov 25 '13 at 21:53
2

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.

kajacx
  • 10,561
  • 4
  • 35
  • 60
  • 1
    @SotiriosDelimanolis: There should be no problem with such an assignment. The danger is when retrieving items from the array (where an implicit cast is added, so you may get ClassCastException), and when storing items in the array (where you may get ArrayStoreException). None of these can occur in this case. Remember that B[] is an array of type Object[] at runtime. – Eyal Schneider Nov 25 '13 at 21:21
  • 1
    @Eyal You are correct. I was testing something unrelated that I thought was related and misjudging the results. Thanks. – Sotirios Delimanolis Nov 25 '13 at 21:40