1

I have created generic array but constructor can not initialize the array. When runtime program throws this exception

 Exception in thread "main" java.lang.RuntimeException:
 Uncompilable source code - generic array creation

how to initialize generic array properly.

class MyList<K,V>{
    K[] k;
    V[] v;
public MyList() {
    k = new K[0];
    v = new V[0];
}

public void add(K key, V val){
    Object[] ob1 = new Object[k.length+1];
    Object[] ob2 = new Object[v.length+1];

    for (int i = 0; i < k.length; i++) {
        ob1[i]=k[i];
        ob2[i]=v[i];
    }
    ob1[k.length]=key;
    ob2[v.length]=val;

    k=(K[]) ob1;
    v=(V[]) ob2;
}

public static void main(String[] args) {
    MyList<Integer,Double> values = new MyList<>();
    values.add(1,0.5);
}
}

why this happen, is there solution?

  • Can't you use a Map (HashMap) for this purpose instead of implementing a new generic array? –  Dec 29 '15 at 13:29
  • Classic question to differentiate between C++ and Java programmer: Is it possible to write `K k = new K()` in template/generics context? –  Dec 29 '15 at 19:28

2 Answers2

1

You can use this Constructor

public MyList(K[] k, V[] v) {
    this.k = k;
    this.v = v;
}


public static void main(String[] args) {
    MyList<Integer,Double> values = new MyList<>(new Integer[0], new Double[0]);
    values.add(1,0.5);
}

This will work

1

Arrays are reifiable types , means there type information should be maintained at runtime.

 k = new K[0];
 v = new V[0];

here, since K and V are generic parameters , type erasure will kick in and erase them to Object.

use newInstance() method in Array class to create generic arrays.

Ramanlfc
  • 7,900
  • 1
  • 14
  • 24