整数GT;如何列出&LT转换;为int []在Java中? [英] How to convert List<Integer> to int[] in Java?

查看:89
本文介绍了整数GT;如何列出&LT转换;为int []在Java中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是类似于这样的问题:
如何INT []转换为整数Java中的[]?

This is similar to this question: How to convert int[] to Integer[] in Java?

我是新来的Java。我如何可以转换列表与LT;整数GT; INT [] 在Java中?我很困惑,因为 List.toArray()实际上返回一个对象[] ,它可以转换为幽冥整数[] 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:


  • 列表&LT; T&GT; .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 :(

虽然 阵列 类抵达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).

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

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