143

这可能是一个简单的,headdesk 类型的问题,但我的第一次尝试出人意料地完全失败了。我想获取一组原始 long 并将其变成一个列表,我试图这样做:

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

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

4

17 回答 17

123

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

long[] arr = { 1, 2, 3, 4 };
List<Long> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
于 2014-04-16T18:41:11.430 回答
117

我发现使用 apache commons lang ArrayUtils(JavaDocMaven 依赖项)很方便

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

它也有反向 API

long[] backToPrimitive = ArrayUtils.toPrimitive(objectArray);

编辑:更新以提供对列表的完整转换,如评论和其他修复所建议的那样。

于 2009-12-29T12:19:13.693 回答
36
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;

List<Long> longs = Arrays.asList(ArrayUtils.toObject(new long[] {1,2,3,4}));
于 2010-06-02T18:32:43.253 回答
35

hallidavejpalecek的想法是正确的——遍历数组——但它们没有利用 : 提供的特性ArrayList:因为在这种情况下列表的大小是已知的,所以你应该在创建ArrayList.

List<Long> list = new ArrayList<Long>(input.length);
for (long n : input)
  list.add(n);

这样,不会创建不必要的数组,ArrayList因为它们太短而被丢弃,并且不会因为ArrayList高估其空间需求而浪费空“槽”。当然,如果您继续向列表中添加元素,则需要一个新的后备数组。

于 2009-04-16T15:48:10.003 回答
19

有点冗长,但这有效:

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

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

于 2009-04-16T00:28:44.567 回答
18

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

import com.google.common.primitives.Longs;

long[] input = someAPI.getSomeLongs();
List<Long> output = Longs.asList(input);
于 2015-08-04T23:05:10.730 回答
7

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

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

for(long l : input) lst.add(l);
于 2009-04-16T00:28:55.627 回答
7

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

至少有两个重要的区别:

  • 结果列表应该是数组上的视图还是应该是列表
  • 结果列表是否应该可以修改

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


创建新列表与在阵列上创建视图

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

List<Long> list = Arrays.stream(array).boxed().collect(Collectors.toList());

但是应该考虑这样做的缺点:具有 1000000long个值的数组将占用大约 8 兆字节的内存。新列表将占用大约 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);

(该方法的实现请参见底部的示例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!

幸运的是,从视图中创建一个副本(即不受数组修改影响的新列表)很简单:

List<Long> copy = new ArrayList<Long>(asList(array));

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


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

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

允许修改列表会引发一些问题:

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?

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

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


下面是一个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();
    }

}

该示例的输出如下所示:

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
于 2018-10-28T13:55:21.230 回答
6

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

long[] input = someAPI.getSomeLongs();
List<Long> = $(input).toList();

如果您关心,请在此处查看

于 2010-01-31T22:04:18.880 回答
6

Java 8 的另一种方式。

long[] input = someAPI.getSomeLongs();
LongStream.of(input).boxed().collect(Collectors.toList()));
于 2016-08-25T09:56:11.603 回答
4

Java 8 的另一种方式

final long[] a = new long[]{1L, 2L};
final List<Long> l = Arrays.stream(a).boxed().collect(Collectors.toList());
于 2015-08-31T05:16:45.067 回答
3

结合 Pavel 和 Tom 的答案,我们得到了这个

   @SuppressWarnings("unchecked")
    public static <T> List<T> asList(final Object array) {
        if (!array.getClass().isArray())
            throw new IllegalArgumentException("Not an array");
        return new AbstractList<T>() {
            @Override
            public T get(int index) {
                return (T) Array.get(array, index);
            }

            @Override
            public int size() {
                return Array.getLength(array);
            }
        };
    }
于 2013-08-01T00:59:37.393 回答
2

如果您想要类似的语义,Arrays.asList那么您需要编写(或使用其他人的)客户实现List(可能通过AbstractList. 它应该具有与 非常相同的实现Arrays.asList,只有 box 和 unbox 值。

于 2009-04-16T00:38:25.170 回答
2

您可以使用变形

Transmorph transmorph = new Transmorph(new DefaultConverters());
List<Long> = transmorph.convert(new long[] {1,2,3,4}, new TypeReference<List<Long>>() {});

例如,如果 source 是一个整数数组,它也可以工作。

于 2010-01-20T06:10:29.983 回答
2

我知道这个问题已经够老了,但是......您也可以编写自己的转换方法:

@SuppressWarnings("unchecked")
public static <T> List<T> toList(Object... items) {

    List<T> list = new ArrayList<T>();

    if (items.length == 1 && items[0].getClass().isArray()) {
        int length = Array.getLength(items[0]);
        for (int i = 0; i < length; i++) {
            Object element = Array.get(items[0], i);
            T item = (T)element;
            list.add(item);
        }
    } else {
        for (Object i : items) {
            T item = (T)i;
            list.add(item);
        }
    }

    return list;
}

使用静态导入包含它后,可能的用法可能是:

    long[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    List<Long> list = toList(array);

或者

    List<Long> list = toList(1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l, 9l);
于 2012-10-12T17:56:00.880 回答
1

虽然可以创建一个新列表并向其中添加所有值(通过 for 循环或流),但我一直在处理非常大的数组并且性能很差。因此,我创建了自己易于使用的原始数组包装类。

例子:

long[] arr = new long[] {1,2,3};
PrimativeList<Long> list = PrimativeList.create(arr); // detects long[] and returns PrimativeList<Long>

System.out.println(list.get(1)); // prints: 2
list.set(2, 15);
System.out.println(arr[2]);  // prints: 15

在这里获取: https ://github.com/Sf298/Sauds-Toolbox/blob/master/src/main/java/PrimitiveArrayWrapper/PrimitiveList.java

注意:我还没有完全测试它,所以如果你发现任何错误/问题,请告诉我。

于 2019-06-16T05:33:46.950 回答
0

你可以使用LongStream

List<Long> longs = LongStream.of(new long[]{1L, 2L, 3L}).boxed()
                             .collect(Collectors.toList());
于 2019-07-21T11:06:47.137 回答