Am I missing something, or do varargs break Arrays.asList?
-
08-07-2019 - |
Question
private void activateRecords(long[] stuff) {
...
api.activateRecords(Arrays.asList(specIdsToActivate));
}
Shouldn't this call to Arrays.asList return a list of Long
s? Instead it is returning a List<long[]>
public static <T> List<T> asList(T... a)
The method signature is consistent with the results, the varargs throws the entire array into the list. It's the same as new ArrayList(); list.add(myArray)
And yes, I know it's meant to be used like this: Arrays.asList(T t1, T t2, T t3)
I guess what I'm getting at, is instead of the varargs form, why can't I just have my old asList method (at least I think this is how it used to work) that would take the contents and put them individually into a list? Any other clean way of doing this?
Solution
That's because long[] and Long[] are different types.
In the first case T is long[], in the second T is Long.
How to fix this? Don't use long[] in the first place?
OTHER TIPS
Autoboxing cannot be done on arrays. You are allowed to do:
private List<Long> array(final long[] lngs) {
List<Long> list = new ArrayList<Long>();
for (long l : lngs) {
list.add(l);
}
return list;
}
or
private List<Long> array(final long[] lngs) {
List<Long> list = new ArrayList<Long>();
for (Long l : lngs) {
list.add(l);
}
return list;
}
(notice that the iterable types are different)
e.g.
Long l = 1l;
but not
Long[] ls = new long[]{1l}