Java将通用LinkedList转换为通用数组 [英] Java Convert Generic LinkedList to Generic Array

查看:243
本文介绍了Java将通用LinkedList转换为通用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,初学者可以说我有一个 LinkedList< String>



通过 toArray()传递给一个数组。即

  LinkedList< String> strList = new LinkedList< String>(); 
String [] strArray = strList.toArray(new String [0]);

但是可以说我有一个 LinkedList< T>
然后我输入以下代码:

  LinkedList< T> tList = new LinkedList< T>(); 
T [] strArray = tList.toArray(new T [0]);

我得到无法创建T 的通用数组错误信息。



我该如何解决这个问题?

具体来说,在我的课程中,我有 LinkedList< AbstractNode< T>>节点,我试图实现getAll()方法,将所有节点作为数组返回。 b

注意PéterTörök的答案为我的问题提供了正确的答案,但对于我而言,只是简单地返回一个ArrayList而不是[]作为Bar提到的,最终使我的代码更加平滑。

Note2 在查看我的代码之后,我甚至不确定是否需要进行任何转换,LinkedList对我所要做的事情很好。 ..: - /

解决方案

类库中使用的解决方法是(使用未经检查的转换)

  public< T> T [] toArray(List  list,T [] a){
if(a.length< list.size()){
a =(T [])java.lang.reflect .Array.newInstance(
a.getClass()。getComponentType(),list.size()));
}
return list.toArray(a);
}

或者 Class 参数而不是数组:

  public< T> T [] toArray(List< T> list,Class< T> k){
return list.toArray(
(T [])java.lang.reflect.Array.newInstance(k,list。尺寸()));

从Java 泛型和集合,第6.4-5章。


无法创建泛型数组Java中最严重的限制之一。因为它非常恼人,所以值得重申其发生的原因:泛型数组是有问题的,因为泛型是通过擦除来实现的,但擦除是有益的,因为它可以缓解进化。 最好的解决方法是使用 ArrayList 或集合框架中的其他类,而不是数组。我们在2.5节中讨论了集合类和数组之间的权衡,并且我们注意到在很多情况下集合比数组更好:因为它们在编译时捕获更多的错误,因为它们提供更多的操作,并且因为它们提供更多的表示的灵活性。到目前为止,数组提供的问题的最佳解决方案是只是说不:使用集合优先于数组。



有时这是行不通的,因为出于兼容性或效率的原因,您需要一个阵列。这个例子发生在集合框架中:为了兼容性,toArray方法将集合转换为数组[...]将集合转换为数组将不起作用。我们可能会尝试的第一个解决方法是添加一个未经检查的演员表,但我们很快会看到这导致更令人困惑的问题。正确的解决方案需要我们去反思。



So for starters lets say that I have a LinkedList<String>,

I can easily convert it to an array via toArray(). i.e.

LinkedList<String> strList = new LinkedList<String>();
String[] strArray = strList.toArray(new String[0]);

But Lets say I have a LinkedList<T> Then I the following code:

LinkedList<T> tList = new LinkedList<T>();
T[] strArray = tList.toArray(new T[0]);

I get the Cannot create a generic array of T error message.

How can I get around this?

Specifically in my class I have LinkedList<AbstractNode<T>> nodes, and I am trying to implement a getAll() method that returns all the nodes as an Array.
Thanks!

Note Péter Török's answer provides the correct answer to my problem, but for me simply returning an ArrayList instead of [] as Bar mentioned, ended up smoothing my code out a lot.
Note2 after looking at my code a bit more i'm not even sure if any conversion was necessary to begin with, LinkedList was fine for what I was trying to do... :-/

解决方案

A workaround which is used in the class library would be (using an unchecked cast)

public <T> T[] toArray(List<T> list, T[] a) {
  if (a.length < list.size()) {
    a = (T[])java.lang.reflect.Array.newInstance(
        a.getClass().getComponentType(), list.size()));
  }
  return list.toArray(a);
}

or, with a Class parameter instead of an array:

public <T> T[] toArray(List<T> list, Class<T> k) {
     return list.toArray(
          (T[])java.lang.reflect.Array.newInstance(k, list.size()));
}

From Java Generics and Collections, chapters 6.4-5.

Inability to create generic arrays is one of the most serious restrictions in Java. Because it is so annoying, it is worth reiterating the reason it occurs: generic arrays are problematic because generics are implemented via erasure, but erasure is beneficial because it eases evolution.

The best workaround is to use ArrayList or some other class from the Collections Framework in preference to an array. We discussed the tradeoffs between collection classes and arrays in Section 2.5, and we noted that in many cases collections are preferable to arrays: because they catch more errors at compile time, because they provide more operations, and because they offer more flexibility in representation. By far, the best solution to the problems offered by arrays is to "just say no": use collections in preference to arrays.

Sometimes this won't work, because you need an array for reasons of compatibility or efficiency. Examples of this occur in the Collections Framework: for compatibility, the method toArray converts a collection to an array [...]

[...] a naïve method to convert a collection to an array will not work. The first fix we might try is to add an unchecked cast, but we will see shortly that this leads to even more perplexing problems. The correct fix will require us to resort to reflection.

这篇关于Java将通用LinkedList转换为通用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆