如何转换列表< Integer>到int []在Java? [英] How to convert List<Integer> to int[] in Java?

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

问题描述

这与此问题类似:
如何将int []转换为整数[] in Java?

我是Java的新手。如何在Java中将 List 转换为 int [] 我很困惑,因为 List.toArray()实际返回一个 Object [] ,可以转换为nether 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;
}

我相信有更好的方法。

推荐答案

不幸的是,我不相信有真正的是一个更好的方式这是由于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:


  • 列表< T> .toArray 整数 int
  • 的转换
  • 不能使用 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 类在genics到达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).

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

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