Creating generic arrays in Java
问题 public K[] toArray() { K[] result = (K[])new Object[this.size()]; int index = 0; for(K k : this) result[index++] = k; return result; } This code does not seem to work, it will throw out an exception: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to ... Could someone tell me how I can create an array with a generic type? Thanks. 回答1: You can't: you must pass the class as an argument: public <K> K[] toArray(Class<K> clazz) { K[] result = (K[])Array.newInstance(clazz,this.size