java 泛型的问题

我想写一个方法list->array 想利用泛型,代码如下


public static <T> T[] list2Array(List<T> list){

    T[] array = (T[])list.toArray(new T[list.size()]);

    return array;

}

也就是传过来的String就返回String数组 Integer就返回Integer数组。但是这个new T[list.size]这里有问题,请问怎么解决?谢谢。


jeck猫
浏览 507回答 3
3回答

HUX布斯

这个Effective Java第二版里有说到, Item25.Because of these fundamental differences, arrays and generics do notmix well. For example, it is illegal to create an array of a generictype, a parameterized type, or a type parameter. None of these arraycreation expressions are legal: new List[], new List[], newE[]. All will result in generic array creation errors at compile time.Generally speaking, arrays and generics don’t mix well. If you findyourself mixing them and getting compile-time errors or warnings, yourfirst impulse should be to replace the arrays with lists.因为数组和泛型不对付, 所以在不做强制类型转换的情况下, 我们是没有办法得到一个泛型数组的实例的, 编译器会限制此类情况发生(new E[], list.toArray());为什么数组和泛型不对付, Effective Java里有例子. 根本原因在于:Arrays are covariant. This scary-sounding word means simply that ifSub is a subtype of Super, then the array type Sub[] is a subtype ofSuper[].给出例子说明我的理解, 类似的代码, 在泛型集合下, 会在静态编译阶段报错; 而泛型数组在运行阶段给出ArrayStoreException:private <T> void doSomethingToGenArr(T[] tArr){&nbsp; &nbsp; Object[] oArr = tArr;&nbsp; &nbsp; oArr[0] = new String("aaa");}private <T> void doSomethingToGenList(List<T> list){&nbsp; &nbsp; List<Object> l1 =&nbsp; list; /* compile error */&nbsp; &nbsp; l1.set(0, new String("aaa"));}@Testpublic void test111(){&nbsp; &nbsp; doSomethingToGenArr(new Integer[2]);}@Testpublic void test112(){&nbsp; &nbsp; doSomethingToGenList(new ArrayList<Integer>());}

慕桂英546537

没有泛型数组,这一说

元芳怎么了

toArray()方法有两种,带参和不带参.带参的情况下,参数就是一个一个泛型数组,如T[] a,相当于你手动构造一个数组,传入方法中.toArray()内部是一个copy的实现.举两个例子.1:String[][] str_a = (String [][]) arr.toArray(new String[0][0]);2 :String[][] a = new String[<size>][size];String [][] str_a = (String [][]) arr.toArray(a);当然 要保证转型成功,不然会引发ClassCastException.--------------------------分割线-------------------------以下是源码中是实现,实际上就是一个copy操作.&nbsp;/**&nbsp; &nbsp; &nbsp;* Returns an array containing all of the elements in this list&nbsp; &nbsp; &nbsp;* in proper sequence (from first to last element).&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* <p>The returned array will be "safe" in that no references to it are&nbsp; &nbsp; &nbsp;* maintained by this list.&nbsp; (In other words, this method must allocate&nbsp; &nbsp; &nbsp;* a new array).&nbsp; The caller is thus free to modify the returned array.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* <p>This method acts as bridge between array-based and collection-based&nbsp; &nbsp; &nbsp;* APIs.&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;* @return an array containing all of the elements in this list in&nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;proper sequence&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; public Object[] toArray() {&nbsp; &nbsp; &nbsp; &nbsp; return Arrays.copyOf(elementData, size);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java