将一个原始long数组转换为Longs列表

Bra*_*ugh 132 java arrays collections boxing

这可能是一个简单的问题,但是我的第一次尝试完全失败了.我想取一个原始long的数组并将其转换为一个列表,我尝试这样做:

long[] input = someAPI.getSomeLongs();
List<Long> inputAsList = Arrays.asList(input); //Total failure to even compile!
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?

Era*_*dan 112

我发现使用apache commons lang ArrayUtils很方便(JavaDoc,Maven依赖)

import org.apache.commons.lang3.ArrayUtils;
...
long[] input = someAPI.getSomeLongs();
Long[] inputBoxed = ArrayUtils.toObject(input);
List<Long> inputAsList = Arrays.asList(inputBoxed);
Run Code Online (Sandbox Code Playgroud)

它也有反向API

long[] backToPrimitive = ArrayUtils.toPrimitive(objectArray);
Run Code Online (Sandbox Code Playgroud)

编辑:已更新,可根据评论和其他修正提示完整转换为列表.

  • 因为人们可以很容易地做`Arrays.asList(ArrayUtils.toObject(input))`. (7认同)
  • 考虑到这会创建一个_array_ of Longs,而不是List_,它不会回答OP的问题而得到我的downvote.这怎么样才能获得56票和令人垂涎的"支票"??? (3认同)
  • @JimJeffers - 谢谢,更新到包括完整的转换.由于OP在他们的问题中包含了`List <Long> = Arrays.asList(inputBoxed)`,我发现重复它是多余的,因为我认为很明显,我想我错了...... (2认同)

mar*_*inj 105

从Java 8开始,您现在可以使用以下流:

long[] arr = {1,2,3,4};
List<Long> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

  • 好一个!不幸的是,有点神秘,`stream`函数只为`int []`,`long []`和`double []`定义. (5认同)
  • 或者,您可以使用“LongStream.of(arr).boxed()...”。 (2认同)
  • `Arrays.stream(arr).boxed().collect(Collectors.toList());`不幸的是,这只能返回`List <Object>` (2认同)

Mar*_*ini 37

import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;

List<Long> longs = Arrays.asList(ArrayUtils.toObject(new long[] {1,2,3,4}));
Run Code Online (Sandbox Code Playgroud)

  • 解释这是什么以及这是否是第三方库会有所帮助. (4认同)

eri*_*son 35

hallidavejpalecek有一个正确的想法 - 迭代一个数组 - 但他们没有利用以下提供的功能ArrayList:因为在这种情况下列表的大小是已知的,你应该在创建时指定它ArrayList.

List<Long> list = new ArrayList<Long>(input.length);
for (long n : input)
  list.add(n);
Run Code Online (Sandbox Code Playgroud)

这样,没有创建不必要的数组只是被ArrayList它们丢弃,因为它们变得太短,并且没有空的"槽"被浪费,因为ArrayList高估了它的空间需求.当然,如果继续向列表中添加元素,则需要新的后备阵列.


hal*_*ave 19

有点冗长,但这有效:

    List<Long> list = new ArrayList<Long>();
    for (long value : input) {
        list.add(value);
    }
Run Code Online (Sandbox Code Playgroud)

在您的示例中,似乎Arrays.asList()将输入解释为long []数组的列表而不是Longs列表.有点令人惊讶,当然.在这种情况下,自动装箱并不像您希望的那样工作.


Tre*_*son 17

作为另一种可能性,Guava库将其作为Longs.asList()其他原始类型的类似实用程序类提供.

import com.google.common.primitives.Longs;

long[] input = someAPI.getSomeLongs();
List<Long> output = Longs.asList(input);
Run Code Online (Sandbox Code Playgroud)


jpa*_*cek 7

不,没有从原始类型数组到其盒装引用类型数组的自动转换.你只能这样做

long[] input = someAPI.getSomeLongs();
List<Long> lst = new ArrayList<Long>();

for(long l : input) lst.add(l);
Run Code Online (Sandbox Code Playgroud)


dfa*_*dfa 6

我正在为这些问题写一个小型库:

long[] input = someAPI.getSomeLongs();
List<Long> = $(input).toList();
Run Code Online (Sandbox Code Playgroud)

在你关心的情况下,请在这里查看.


rav*_*ter 6

Java 8的另一种方式.

long[] input = someAPI.getSomeLongs();
LongStream.of(input).boxed().collect(Collectors.toList()));
Run Code Online (Sandbox Code Playgroud)


Mar*_*o13 6

问题询问如何将数组转换为列表。到目前为止,大多数答案都显示了如何创建与数组相同的内容或引用第三方库的列表。但是,这种转换有简单的内置选项。其中一些已经在其他答案中得到了概述(例如,这个答案)。但是,我想指出并详细说明此处实施的自由度,并说明潜在的好处,缺点和警告。

至少有两个重要的区别:

  • 结果列表应该是数组的视图还是列表
  • 无论结果列表应该修改或不

这些选项将在此处快速总结,并且在该答案的底部显示了完整的示例程序。


创建新列表与在数组上创建视图

当结果应为列表时,则可以使用其他答案中的一种方法:

List<Long> list = Arrays.stream(array).boxed().collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

但是,应该考虑这样做的弊端:具有1000000 long值的数组将占用大约8 MB的内存。新的名单将同时占用大约8兆字节。当然,创建此列表时必须遍历整个数组。在许多情况下,根本不需要创建新列表。相反,在数组上创建视图就足够了:

// This occupies ca. 8 MB
long array[] = { /* 1 million elements */ }

// Properly implemented, this list will only occupy a few bytes,
// and the array does NOT have to be traversed, meaning that this
// operation has nearly ZERO memory- and processing overhead:
List<Long> list = asList(array);
Run Code Online (Sandbox Code Playgroud)

(有关toList方法的实现,请参见底部的示例)

在数组上具有视图的含义是,数组中的更改将在列表中可见:

long array[] = { 12, 34, 56, 78 };
List<Long> list = asList(array);

System.out.println(list.get(1)); // This will print 34

// Modify the array contents:
array[1] = 12345;

System.out.println(list.get(1)); // This will now print 12345!
Run Code Online (Sandbox Code Playgroud)

幸运的是,从视图创建副本(即不受阵列修改影响的列表)很简单:

List<Long> copy = new ArrayList<Long>(asList(array));
Run Code Online (Sandbox Code Playgroud)

现在,这是一个真实的副本,等效于上面显示的基于流的解决方案所实现的副本。


创建可修改视图或不可修改视图

在很多情况下,列表为只读就足够了。结果列表的内容通常不会被修改,而只会传递给仅读取列表的下游处理。

允许对列表进行修改会引起一些问题:

long array[] = { 12, 34, 56, 78 };
List<Long> list = asList(array);

list.set(2, 34567);           // Should this be possible?
System.out.println(array[2]); // Should this print 34567?
list.set(3, null);            // What should happen here?
list.add(99999);              // Should this be possible?
Run Code Online (Sandbox Code Playgroud)

可以在可修改的阵列上创建列表视图。这意味着列表中的更改(例如在某个索引处设置新值)将在数组中可见。

但是无法创建在结构上可修改的列表视图。这意味着不可能执行影响列表大小的操作。这仅仅是因为基础数组的大小无法更改。


以下是MCVE,显示了不同的实现选项以及使用结果列表的可能方式:

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.RandomAccess;

public class PrimitiveArraysAsLists
{
    public static void main(String[] args)
    {
        long array[] = { 12, 34, 56, 78 };

        // Create VIEWS on the given array
        List<Long> list = asList(array);
        List<Long> unmodifiableList = asUnmodifiableList(array);

        // If a NEW list is desired (and not a VIEW on the array), this
        // can be created as well:
        List<Long> copy = new ArrayList<Long>(asList(array));

        System.out.println("array           : " + Arrays.toString(array));
        System.out.println("list            : " + list);
        System.out.println("unmodifiableList: " + unmodifiableList);
        System.out.println("copy            : " + copy);        

        // Modify a value in the array. The changes will be visible
        // in the list and the unmodifiable list, but not in
        // the copy.
        System.out.println("Changing value at index 1 of the array...");
        array[1] = 34567;

        System.out.println("array           : " + Arrays.toString(array));
        System.out.println("list            : " + list);
        System.out.println("unmodifiableList: " + unmodifiableList);
        System.out.println("copy            : " + copy);        

        // Modify a value of the list. The changes will be visible
        // in the array and the unmodifiable list, but not in
        // the copy.
        System.out.println("Changing value at index 2 of the list...");
        list.set(2, 56789L);

        System.out.println("array           : " + Arrays.toString(array));
        System.out.println("list            : " + list);
        System.out.println("unmodifiableList: " + unmodifiableList);
        System.out.println("copy            : " + copy);        


        // Certain operations are not supported:
        try
        {
            // Throws an UnsupportedOperationException: This list is 
            // unmodifiable, because the "set" method is not implemented
            unmodifiableList.set(2, 23456L);
        }
        catch (UnsupportedOperationException e) 
        {
            System.out.println("Expected: " + e);
        }

        try
        {
            // Throws an UnsupportedOperationException: The size of the
            // backing array cannot be changed
            list.add(90L);
        }
        catch (UnsupportedOperationException e) 
        {
            System.out.println("Expected: " + e);
        }


        try
        {
            // Throws a NullPointerException: The value 'null' cannot be  
            // converted to a primitive 'long' value for the underlying array
            list.set(2, null);
        }
        catch (NullPointerException e)
        {
            System.out.println("Expected: " + e);
        }

    }

    /**
     * Returns an unmodifiable view on the given array, as a list.
     * Changes in the given array will be visible in the returned
     * list.
     *  
     * @param array The array
     * @return The list view
     */
    private static List<Long> asUnmodifiableList(long array[])
    {
        Objects.requireNonNull(array);
        class ResultList extends AbstractList<Long> implements RandomAccess
        {
            @Override
            public Long get(int index)
            {
                return array[index];
            }

            @Override
            public int size()
            {
                return array.length;
            }
        };
        return new ResultList();
    }

    /**
     * Returns a view on the given array, as a list. Changes in the given 
     * array will be visible in the returned list, and vice versa. The
     * list does not allow for <i>structural modifications</i>, meaning
     * that it is not possible to change the size of the list.
     *  
     * @param array The array
     * @return The list view
     */
    private static List<Long> asList(long array[])
    {
        Objects.requireNonNull(array);
        class ResultList extends AbstractList<Long> implements RandomAccess
        {
            @Override
            public Long get(int index)
            {
                return array[index];
            }

            @Override
            public Long set(int index, Long element)
            {
                long old = array[index];
                array[index] = element;
                return old;
            }

            @Override
            public int size()
            {
                return array.length;
            }
        };
        return new ResultList();
    }

}
Run Code Online (Sandbox Code Playgroud)

示例的输出如下所示:

array           : [12, 34, 56, 78]
list            : [12, 34, 56, 78]
unmodifiableList: [12, 34, 56, 78]
copy            : [12, 34, 56, 78]
Changing value at index 1 of the array...
array           : [12, 34567, 56, 78]
list            : [12, 34567, 56, 78]
unmodifiableList: [12, 34567, 56, 78]
copy            : [12, 34, 56, 78]
Changing value at index 2 of the list...
array           : [12, 34567, 56789, 78]
list            : [12, 34567, 56789, 78]
unmodifiableList: [12, 34567, 56789, 78]
copy            : [12, 34, 56, 78]
Expected: java.lang.UnsupportedOperationException
Expected: java.lang.UnsupportedOperationException
Expected: java.lang.NullPointerException
Run Code Online (Sandbox Code Playgroud)


Jin*_*won 5

Java 8 的另一种方式

final long[] a = new long[]{1L, 2L};
final List<Long> l = Arrays.stream(a).boxed().collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

  • 这与[此现有答案](/sf/answers/1618234691/)相同。 (3认同)