如何在 Java 中将 List<Integer> 转换为 int[]?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/960431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:35:58  来源:igfitidea点击:

How to convert List<Integer> to int[] in Java?

javaarrayscollections

提问by

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

这类似于这个问题: How to convert int[] to Integer[] in Java?

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[].

我是 Java 新手。我怎么能转换List<Integer>int[]Java中?我很困惑,因为List.toArray()实际上返回了一个Object[],它可以投射到下界Integer[]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.

我相信有更好的方法来做到这一点。

采纳答案by Jon Skeet

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

不幸的是,我不相信有真的这样做由于Java的处理基本类型,拳击,数组和仿制药的性质的更好的方法。特别是:

  • List<T>.toArraywon't work because there's no conversion from Integerto int
  • You can't use intas a type argument for generics, so it would haveto be an int-specific method (or one which used reflection to do nasty trickery).
  • List<T>.toArray不会工作,因为没有从Integer到的转换int
  • 您不能int用作泛型的类型参数,因此它必须是一个int特定的方法(或使用反射来做令人讨厌的诡计的方法)。

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 :(

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

Even though the Arraysclass 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).

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

回答by neesh

There is really no way of "one-lining" what you are trying to do because toArray returns an Object[] and you cannot cast from Object[] to int[] or Integer[] to int[]

真的没有办法“单行”你想要做什么,因为 toArray 返回一个 Object[] 并且你不能从 Object[] 转换为 int[] 或 Integer[] 到 int[]

回答by Eddie

The easiest way to do this is to make use of Apache Commons Lang. It has a handy ArrayUtils class that can do what you want. Use the toPrimitivemethod with the overload for an array of Integers.

最简单的方法是使用Apache Commons Lang。它有一个方便的 ArrayUtils 类,可以做你想做的事。将该toPrimitive方法与Integers数组重载一起使用。

List<Integer> myList;
 ... assign and fill the list
int[] intArray = ArrayUtils.toPrimitive(myList.toArray(new Integer[myList.size()]));

This way you don't reinvent the wheel. Commons Lang has a great many useful things that Java left out. Above, I chose to create an Integer list of the right size. You can also use a 0-length static Integer array and let Java allocate an array of the right size:

这样你就不会重新发明轮子。Commons Lang 有很多 Java 遗漏的有用的东西。上面,我选择创建一个大小合适的整数列表。您还可以使用长度为 0 的静态整数数组,并让 Java 分配一个合适大小的数组:

static final Integer[] NO_INTS = new Integer[0];
   ....
int[] intArray2 = ArrayUtils.toPrimitive(myList.toArray(NO_INTS));

回答by Eddie

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

Slight change to your code to avoid expensive list indexing (since a List is not necessarily an ArrayList, but could be a linked list, for which random access is expensive)

对代码稍作更改以避免昂贵的列表索引(因为 List 不一定是 ArrayList,但可能是链表,随机访问的成本很高)

回答by ColinD

In addition to Commons Lang, you can do this with Guava's method Ints.toArray(Collection<Integer> collection):

除了 Commons Lang 之外,您还可以使用Guava的方法来做到这一点Ints.toArray(Collection<Integer> collection)

List<Integer> list = ...
int[] ints = Ints.toArray(list);

This saves you having to do the intermediate array conversion that the Commons Lang equivalent requires yourself.

这使您不必执行 Commons Lang 等效项要求您自己进行的中间数组转换。

回答by dfa

try also Dollar(check this revision):

也试试美元检查这个修订版):

import static com.humaorie.dollar.Dollar.*
...

List<Integer> source = ...;
int[] ints = $(source).convert().toIntArray();

回答by DennisTemper

I would recommend you to use List<?>skeletal implementation from the java collections API, it appears to be quite helpful in this particular case:

我建议您使用List<?>java 集合 API 中的骨架实现,它在这种特殊情况下似乎很有帮助:

package mypackage;

import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Test {

//Helper method to convert int arrays into Lists
static List<Integer> intArrayAsList(final int[] a) {
    if(a == null)
        throw new NullPointerException();
    return new AbstractList<Integer>() {

        @Override
        public Integer get(int i) {
            return a[i];//autoboxing
        }
        @Override
        public Integer set(int i, Integer val) {
            final int old = a[i];
            a[i] = val;//auto-unboxing
            return old;//autoboxing
        }
        @Override
        public int size() {
            return a.length;
        }
    };
}

public static void main(final String[] args) {
    int[] a = {1, 2, 3, 4, 5};
    Collections.reverse(intArrayAsList(a));
    System.out.println(Arrays.toString(a));
}
}

Beware of boxing/unboxing drawbacks

当心装箱/拆箱缺点

回答by gerardw

int[] ret = new int[list.size()];       
Iterator<Integer> iter = list.iterator();
for (int i=0; iter.hasNext(); i++) {       
    ret[i] = iter.next();                
}                                        
return ret;                              

回答by NimChimpsky

Using a lambda you could do this (compiles in jdk lambda):

使用 lambda 你可以做到这一点(在 jdk lambda 中编译):

public static void main(String ars[]) {
        TransformService transformService = (inputs) -> {
            int[] ints = new int[inputs.size()];
            int i = 0;
            for (Integer element : inputs) {
                ints[ i++ ] = element;
            }
            return ints;
        };

        List<Integer> inputs = new ArrayList<Integer>(5) { {add(10); add(10);} };

        int[] results = transformService.transform(inputs);
    }

    public interface TransformService {
        int[] transform(List<Integer> inputs);
    }

回答by Loduwijk

I'll throw one more in here. I've noticed several uses of for loops, but you don't even need anything inside the loop. I mention this only because the original question was trying to find less verbose code.

我这里再扔一个。我注意到 for 循环的几种用途,但您甚至不需要循环内的任何东西。我提到这一点只是因为最初的问题是试图找到不那么冗长的代码。

int[] toArray(List<Integer> list) {
    int[] ret = new int[ list.size() ];
    int i = 0;
    for( Iterator<Integer> it = list.iterator(); 
         it.hasNext(); 
         ret[i++] = it.next() );
    return ret;
}

If Java allowed multiple declarations in a for loop the way C++ does, we could go a step further and do for(int i = 0, Iterator it...

如果 Java 允许在 for 循环中像 C++ 那样有多个声明,我们可以更进一步,执行 for(int i = 0, Iterator it...

In the end though (this part is just my opinion), if you are going to have a helping function or method to do something for you, just set it up and forget about it. It can be a one-liner or ten; if you'll never look at it again you won't know the difference.

最后(这部分只是我的意见),如果您打算有一个帮助功能或方法为您做某事,只需设置它并忘记它。它可以是一个或十个;如果你永远不会再看它,你就不会知道其中的区别。