Java 将原始 long 数组转换为 Long 列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/754294/
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 19:05:11  来源:igfitidea点击:

Convert an array of primitive longs into a List of Longs

javaarrayscollectionsboxing

提问by Brandon Yarbrough

This may be a bit of an easy, headdesk sort of question, but my first attempt surprisingly completely failed to work. I wanted to take an array of primitive longs and turn it into a list, which I attempted to do like this:

这可能是一个简单的前台类型的问题,但我的第一次尝试令人惊讶地完全失败了。我想获取一个原始 long 数组并将其转换为一个列表,我尝试这样做:

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

What's the right way to do this?

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

采纳答案by Eran Medan

I found it convenient to do using apache commons lang ArrayUtils (JavaDoc, Maven dependency)

我发现使用 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);

it also has the reverse API

它也有反向 API

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

EDIT:updated to provide a complete conversion to a list as suggested by comments and other fixes.

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

回答by hallidave

A bit more verbose, but this works:

有点冗长,但这有效:

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

In your example it appears that Arrays.asList() is interpreting the input as list of long[] arrays instead of a list of Longs. A bit surprising, for sure. Autoboxing just doesn't work the way you want it to in this case.

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

回答by jpalecek

No, there is no automatic conversion from array of primitive type to array of their boxed reference types. You can only do

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

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

for(long l : input) lst.add(l);

回答by Tom Hawtin - tackline

If you want similar semantics to Arrays.asListthen you'll need to write (or use someone else's) customer implementation of List(probably through AbstractList. It should have much the same implementation as Arrays.asList, only box and unbox values.

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

回答by erickson

hallidaveand jpalecekhave the right idea—iterating over an array—but they don't take advantage of a feature provided by ArrayList: since the size of the list is knownin this case, you should specify it when you create the ArrayList.

Hallidavejpalecek有正确的想法——迭代数组——但他们没有利用由 提供的功能ArrayList:由于在这种情况下列表的大小是已知的,因此您应该在创建ArrayList.

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

This way, no unnecessary arrays are created only to be discarded by the ArrayListbecause they turn out to be too short, and no empty "slots" are wasted because ArrayListoverestimated its space requirements. Of course, if you continue to add elements to the list, a new backing array will be needed.

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

回答by cchabanois

You can use transmorph:

您可以使用变形

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

It also works if source is an array of ints for example.

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

回答by dfa

I'm writing a small library for these problems:

我正在为这些问题编写一个小型图书馆:

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

In the case you care check it here.

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

回答by Marco Pelegrini

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

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

回答by Pavel Netesa

I know this question is old enough, but... you can also write your own conversion method:

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

@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;
}

After you include it using static import, possible usages could be:

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

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

or

或者

    List<Long> list = toList(1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l, 9l);

回答by Duncan McGregor

Combining Pavel and Tom's answers we get this

结合 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);
            }
        };
    }