简体   繁体   English

在泛型方法中创建通用数组实例

[英]Creating a generic array instance in a generic method

I'm trying to build a helper method to turn the two line list to array conversion into a single line. 我正在尝试构建一个帮助方法,将两个行列表转换为数组转换为一行。 The problem I've ran into is that I'm not sure how to create aa T[] instance. 我遇到的问题是我不确定如何创建一个T []实例。

I've tried 我试过了

Array.newInstance(T.class, list.size) but I can't feed it T.class.. Array.newInstance(T.class, list.size)但是我无法为它提供T.class ..

Also tried new T[](list.size) but it doesn't like the parameters. 还尝试了new T[](list.size)但它不喜欢参数。

public <T> T[] ConvertToArray(List<T> list)
{
   T[] result = ???

   result = list.toArray(result);

   return result;
}

Any other ideas? 还有其他想法吗?

Thanks 谢谢

You can't mix generics and arrays like that. 你不能混淆泛型和那样的数组。 Generics have compile-time checking, arrays have runtime checking, and those approaches are mostly incompatible. 泛型具有编译时检查,数组具有运行时检查,并且这些方法大多不兼容。 At first I suggested this: 起初我建议:

@SuppressWarnings("unchecked")
public <T> T[] ConvertToArray(List<T> list)
{      
   Object[] result = new Object[list.size()];
   result = list.toArray(result);
   return (T[])result;
}

This is wrong in a stealthy way, as at least one other person on here thought it would work! 这是一种隐秘的错误,因为至少有一个其他人认为它会起作用! However when you run it you get an incompatible type error, because you can't cast an Object[] to an Integer[]. 但是,当您运行它时会出现不兼容的类型错误,因为您无法将Object []强制转换为Integer []。 Why can't we get T.class and create an array the right type? 为什么我们不能获得T.class并创建一个正确类型的数组? Or do new T[] ? 或者做new T[]

Generics use type erasure to preserve backward compatibility. 泛型使用类型擦除来保持向后兼容性。 They are checked at compile time, but stripped from the runtime, so the bytecode is compatible with pre-generics JVMs. 它们在编译时检查,但从运行时剥离,因此字节码与预泛化JVM兼容。 This means you cannot have class knowledge of a generic variable at runtime! 这意味着您无法在运行时获得泛型变量的类知识!

So while you can guarantee that T[] result will be of the type Integer[] ahead of time, the code list.toArray(result); 因此,虽然您可以保证T[] result将提前为Integer []类型,但代码list.toArray(result); (or new T[] , or Array.newInstance(T.class, list.size()); ) will only happen at runtime, and it cannot know what T is! (或new T[] ,或者Array.newInstance(T.class, list.size()); )只会在运行时发生,而且它不知道T是什么!

Here's a version that does work, as a reward for reading that lecture: 下面是工作,作为报酬,用于读取讲座版本:

public static <T> T[] convertToArray(List<?> list, Class<T> c) {
    @SuppressWarnings("unchecked")
    T[] result = (T[]) Array.newInstance(c, list.size());
    result = list.toArray(result);
    return (T[]) result;
}

Note that we have a second parameter to provide the class at runtime (as well as at compile time via generics). 请注意,我们有第二个参数在运行时(以及通过泛型编译时)提供类。 You would use this like so: 你会像这样使用它:

Integer[] arrayOfIntegers = convertToArray(listOfIntegers, Integer.class);

Is this worth the hassle? 这值得麻烦吗? We still need to suppress a warning, so is it definitely safe? 我们仍然需要抑制警告,所以它绝对安全吗?

My answer is yes. 我的回答是肯定的。 The warning generated there is just an "I'm not sure" from the compiler. 生成的警告只是来自编译器的“我不确定”。 By stepping through it, we can confirm that that cast will always succeed - even if you put the wrong class in as the second parameter, a compile-time warning is thrown. 通过单步执行,我们可以确认该转换将始终成功 - 即使您将错误的类作为第二个参数,也会抛出编译时警告。

The major advantage of doing this is that we have centralised the warning to one single place. 这样做的主要优点是我们已将警告集中到一个地方。 We only need to prove this one place correct, and we know the code will always succeed. 我们只需要证明这一个地方是正确的,我们知道代码将永远成功。 To quote the Java documentation: 引用Java文档:

the language is designed to guarantee that if your entire application has been compiled without unchecked warnings using javac -source 1.5, it is type safe [1] 该语言旨在保证如果您的整个应用程序使用javac -source 1.5编译时没有未经检查的警告,则它是类型安全的[1]

So now rather than having these warnings all over your code, it's just in one place, and you can use this without having to worry - there's a massively reduced risk of you making a mistake by using it. 所以现在不是在你的代码中都有这些警告,而是只在一个地方,你可以使用它而不必担心 - 通过使用它可以大大降低你犯错误的风险。

You may also want to look at this SO answer which explains the issue in more depth, and this answer which was my crib sheet when writing this. 您可能还想看看这个SO答案 ,它更深入地解释了这个问题, 这个答案是我写这篇文章时的床单。 As well as the already cited Java documentation , another handy reference I used was this blog post by Neal Gafter, ex senior staff engineer at Sun Microsystems and co-designer of 1.4 and 5.0's language features. 除了已经引用的Java文档之外 ,我使用的另一个方便的参考是Neal Gafter的博客文章 ,他是Sun Microsystems的高级工程师,以及1.4和5.0语言功能的共同设计师。

And of course, thanks to ShaneC who rightly pointed out that my first answer failed at runtime! 当然,感谢ShaneC正确地指出我的第一个答案在运行时失败了!

If you can't pass in T.class , then you're basically screwed. 如果你不能传入T.class ,那么你基本上是搞砸了。 Type erasure means you simply won't know the type of T at execution time. 类型擦除意味着您在执行时根本不知道T的类型。

Of course there are other ways of specifying types, such as super type tokens - but my guess is that if you can't pass in T.class , you won't be able to pass in a type token either. 当然还有其他指定类型的方法,比如超类型令牌 - 但我的猜测是,如果你不能传入T.class ,你也无法传入类型令牌。 If you can, then that's great :) 如果可以,那就太好了:)

The problem is that because of type erasure, a List does not know it's component type at runtime, while the component type is what you would need to create the array. 问题是由于类型擦除,List在运行时不知道它的组件类型,而组件类型是创建数组所需的类型。

So you have the two options you will find all over the API: 因此,您可以在API中找到两个选项:

The only other possibility I can think of would be a huge hassle: 我能想到的唯一另一种可能性是一个巨大的麻烦:

  • Iterate over all items of the list and find the "Greatest Common Divisor", the most specific class or interface that all the items extend or implement. 迭代列表中的所有项目并找到“最大公约数”,这是所有项目扩展或实现的最具体的类或接口。
  • Create an array of that type 创建该类型的数组

But that's going to be a lot more lines than your two (and it may also lead to client code making invalid assumptions). 但这将比你的两行更多(并且它也可能导致客户端代码做出无效的假设)。

Does this really need to be changed to a one-liner? 这真的需要改成单行吗? With any concrete class, you can already do a List to Array conversion in one line: 对于任何具体类,您可以在一行中执行List to Array转换:

MyClass[] result = list.toArray(new MyClass[0]);

Granted, this won't work for generic arguments in a class. 当然,这不适用于类中的泛型参数。

See Joshua Bloch's Effective Java Second Edition , Item 25: Prefer lists to array (pp 119-123). 参见Joshua Bloch的Effective Java Second Edition ,第25项:首选列表到数组(第119-123页)。 Which is part of the sample chapter PDF . 这是PDF示例章节的一部分。

Here's the closest I can see to doing what you want. 这是我能看到的最接近你想要的东西。 This makes the big assumptions that you know the class at the time you write the code and that all the objects in the list are the same class, ie no subclasses. 这使得您在编写代码时知道类的大假设以及列表中的所有对象都是同一个类,即没有子类。 I'm sure this could be made more sophisticated to relieve the assumption about no subclasses, but I don't see how in Java you could get around the assumption of knowing the class at coding time. 我确信这可以变得更复杂,以减轻没有子类的假设,但我不知道如何在Java中你可以绕过在编码时知道类的假设。

package play1;

import java.util.*;

public class Play
{
  public static void main (String args[])
  {
    List<String> list=new ArrayList<String>();
    list.add("Hello");
    list.add("Shalom");
    list.add("Godspidanya");

    ArrayTool<String> arrayTool=new ArrayTool<String>();
    String[] array=arrayTool.arrayify(list);

    for (int x=0;x<array.length;++x)
    {
      System.out.println(array[x]);
    }
  }
}
class ArrayTool<T>
{
  public T[] arrayify(List<T> list)
  {
    Class clazz=list.get(0).getClass();
    T[] a=(T[]) Array.newInstance(clazz, list.size());
    return list.toArray(a);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM