Java 将 long 数组转换为 ArrayList<Long>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1979767/
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
Converting an array of long to ArrayList<Long>
提问by ripper234
This sadly doesn't work:
遗憾的是,这不起作用:
long[] longs = new long[]{1L};
ArrayList<Long> longArray = new ArrayList<Long>(longs);
Is there a nicer way except adding them manually?
除了手动添加它们之外,还有更好的方法吗?
采纳答案by Bozho
Using ArrayUtilsfrom apache commons-lang
在 apache commons-lang 中使用ArrayUtils
long[] longs = new long[]{1L};
Long[] longObjects = ArrayUtils.toObject(longs);
List<Long> longList = java.util.Arrays.asList(longObjects);
回答by Billy Bob Bain
You can avoid the copy by implementing an AbstractList
via a static factory. All changes to the list write through to the array and vice-versa.
您可以通过实现一个AbstractList
via 静态工厂来避免复制。对列表的所有更改都会写入数组,反之亦然。
Create this method somewhere.
在某处创建此方法。
public static List<Long> asList(final long[] l) {
return new AbstractList<Long>() {
public Long get(int i) {return l[i];}
// throws NPE if val == null
public Long set(int i, Long val) {
Long oldVal = l[i];
l[i] = val;
return oldVal;
}
public int size() { return l.length;}
};
}
Then just invoke this method to create the array. You will need to use the interface List
and not the implementation ArrayList
in your declaration.
然后只需调用此方法来创建数组。您将需要在声明中使用接口List
而不是实现ArrayList
。
long[] longs = new long[]{1L, 2L, 3L};
List<Long> longArray = asList(longs);
I picked up this technique from the language guide.
我从语言指南中学到了这个技巧。
回答by ripper234
Bozho's answer is good, but I dislike copying the array twice. I ended up rolling my own utility method for this:
Bozho 的回答很好,但我不喜欢将数组复制两次。我最终为此推出了自己的实用方法:
public static ArrayList<Long> convertArray(long[] array) {
ArrayList<Long> result = new ArrayList<Long>(array.length);
for (long item : array)
result.add(item);
return result;
}
回答by Esko
Since others have suggested external libraries, here's the Google Guava librariesway:
由于其他人建议使用外部库,这里是Google Guava 库方式:
long[] longs = {1L, 2L, 3L};
List<Long> longList = com.google.common.primitives.Longs.asList(longs);
回答by Paul McKenzie
Note use of java.lang.Long
, not long
注意使用java.lang.Long
, 不是long
final Long[] longs = new Long[]{1L};
final List<Long> longArray = Arrays.asList(longs);
Doesn't add any thirdparty dependencies.
不添加任何第三方依赖项。
回答by dfa
回答by Coder_Roc
In JDK 1.8,with Lambda and Stream API,We can do it like this:
在 JDK 1.8 中,使用 Lambda 和 Stream API,我们可以这样做:
long[] longArr = {3L, 4L, 5L, 6L, 7L};
List<Long> longBoxArr = Arrays.stream(longArr).boxed().collect(Collectors.toList());