如何转换 List<Integer>到 Java 中的 int[]? [英] How to convert List&lt;Integer&gt; to int[] in Java?

查看:30
本文介绍了如何转换 List<Integer>到 Java 中的 int[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我是 Java 新手.如何在 Java 中将 List 转换为 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.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 :(

即使 Arrays 类在泛型进入 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).

这篇关于如何转换 List<Integer>到 Java 中的 int[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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