如何转换列表<整数>在 Java 中转换为 int[]?

2022-01-31 00:00:00 arrays collections java

这类似于这个问题:如何在Java中将int[]转换为Integer[]?

我是 Java 新手.如何在 Java 中将 List<Integer> 转换为 int[]?我很困惑,因为 List.toArray() 实际上返回了一个 Object[],它可以转换为下一个 Integer[]>int[].

I'm new to Java. How can i convert a List<Integer> to int[] in Java? I'm confused because List.toArray() actually returns an Object[], which can be cast to nether Integer[] or int[].

现在我正在使用循环来执行此操作:

Right now I'm using a loop to do so:

int[] toIntArray(List<Integer> list){
  int[] ret = new int[list.size()];
  for(int i = 0;i < ret.length;i++)
    ret[i] = list.get(i);
  return ret;
}

我确信有更好的方法来做到这一点.

I'm sure there's a better way to do this.

推荐答案

不幸的是,由于 Java 处理原始类型的性质,我不认为真的有 更好的方法、装箱、数组和泛型.特别是:

Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:

  • List<T>.toArray 不起作用,因为没有从 Integerint
  • 的转换
  • 您不能将 int 用作泛型的类型参数,因此 必须 成为特定于 int 的方法(或一个使用反射来做恶作剧的人).
  • List<T>.toArray won't work because there's no conversion from Integer to int
  • You can't use int as a type argument for generics, so it would have to be an int-specific method (or one which used reflection to do nasty trickery).

我相信有些库为所有原始类型自动生成了这种方法的版本(即,有一个为每种类型复制的模板).这很丑陋,但恐怕就是这样:(

I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there's a template which is copied for each type). It's ugly, but that's the way it is I'm afraid :(

即使 数组 类在泛型进入 Java 之前就出现了,如果它在今天被引入,它仍然必须包含所有可怕的重载(假设你想使用原始数组).

Even though the Arrays class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays).

相关文章