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?