将整数列表转换为整型数组

14

有没有一种方法可以将整数列表转换为 int 数组(而不是 integer)? 类似于 List 到 int [] 的方式?而不需要循环遍历列表并手动将整数转换为 int。


这里的循环有什么问题? - Santosh Gokak
5个回答

43

+1,我也正要发同样的帖子。 :-) - missingfaktor
有一个打字错误,应该是 ArrayUtils - gpeche
在调用 toArray() 之前,为了保证安全,您需要从列表中删除所有的 null 元素。 - Sean Patrick Floyd

4
我相信你可以在第三方库中找到一些东西,但我不认为Java标准库中有任何内置的内容。
我建议你编写一个实用函数来完成它,除非你需要大量类似的功能(在这种情况下,找到相关的第三方库是值得的)。请注意,您需要确定如何处理列表中的null引用,这显然无法在int数组中准确表示。

1

不需要 :)

你需要遍历这个列表。这应该不会太痛苦。


1

这是一个实用方法,将整数集合转换为整数数组。如果输入为空,则返回null。如果输入包含任何null值,则创建一个防御性副本,从中删除所有null值。原始集合保持不变。

public static int[] toIntArray(final Collection<Integer> data){
    int[] result;
    // null result for null input
    if(data == null){
        result = null;
    // empty array for empty collection
    } else if(data.isEmpty()){
        result = new int[0];
    } else{
        final Collection<Integer> effective;
        // if data contains null make defensive copy
        // and remove null values
        if(data.contains(null)){
            effective = new ArrayList<Integer>(data);
            while(effective.remove(null)){}
        // otherwise use original collection
        }else{
            effective = data;
        }
        result = new int[effective.size()];
        int offset = 0;
        // store values
        for(final Integer i : effective){
            result[offset++] = i.intValue();
        }
    }
    return result;
}

更新:Guava提供了一种简单的方法实现这个功能:

int[] array = Ints.toArray(data);

参考资料:


-3
    List<Integer>  listInt = new ArrayList<Integer>();

    StringBuffer strBuffer = new StringBuffer();

    for(Object o:listInt){
        strBuffer.append(o);
    }

    int [] arrayInt = new int[]{Integer.parseInt(strBuffer.toString())};

我认为这应该解决你的问题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接