开发者

Converting an array of long to ArrayList<Long>

This sadly doesn't work:

long[] longs = new long[]{1L};
ArrayList<Long> longArray = n开发者_JS百科ew ArrayList<Long>(longs);

Is there a nicer way except adding them manually?


Using ArrayUtils from apache commons-lang

long[] longs = new long[]{1L};
Long[] longObjects = ArrayUtils.toObject(longs);
List<Long> longList = java.util.Arrays.asList(longObjects);


Since others have suggested external libraries, here's the Google Guava libraries way:

long[] longs = {1L, 2L, 3L};
List<Long> longList = com.google.common.primitives.Longs.asList(longs);

Relevant javadoc for Longs.


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.

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.

long[] longs = new long[]{1L, 2L, 3L};
List<Long> longArray = asList(longs);

I picked up this technique from the language guide.


Note use of java.lang.Long, not long

final Long[] longs = new Long[]{1L};
final List<Long> longArray = Arrays.asList(longs);

Doesn't add any thirdparty dependencies.


Bozho's answer is good, but I dislike copying the array twice. I ended up rolling my own utility method for this:

public static ArrayList<Long> convertArray(long[] array) {
  ArrayList<Long> result = new ArrayList<Long>(array.length);
  for (long item : array)
    result.add(item);
  return result;
}


In JDK 1.8,with Lambda and Stream API,We can do it like this:

long[] longArr = {3L, 4L, 5L, 6L, 7L};
List<Long> longBoxArr = Arrays.stream(longArr).boxed().collect(Collectors.toList());


using Dollar you can do this conversion in only 1 line of code:

long[] longs = new long[]{1L};
List<Long> longList = $(longs).toList();

you can also box them easily:

Long[] arrayOfLongs = $(longs).toArray();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜