简体   繁体   English

我错过了什么,或者varargs打破Arrays.asList?

[英]Am I missing something, or do varargs break Arrays.asList?

  private void activateRecords(long[] stuff) {
    ...
    api.activateRecords(Arrays.asList(specIdsToActivate));
  }

Shouldn't this call to Arrays.asList return a list of Long s? 不应该调用Arrays.asList返回Long s的列表吗? Instead it is returning a List<long[]> 而是返回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. 方法签名与结果一致,varargs将整个数组抛出到列表中。 It's the same as new ArrayList(); list.add(myArray) 它与new ArrayList(); list.add(myArray)相同new ArrayList(); list.add(myArray) 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) new ArrayList(); list.add(myArray)是的,我知道它的意思是这样使用: 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? 我想我得到的是,而不是varargs形式,为什么我不能只使用我的旧asList方法(至少我认为这是它以前的工作方式),它将获取内容并将它们单独放入一个列表? Any other clean way of doing this? 这样做还有其他干净的方法吗?

That's because long[] and Long[] are different types. 那是因为long []和Long []是不同的类型。

In the first case T is long[], in the second T is Long. 在第一种情况下,T是long [],在第二种情况下T是Long。

How to fix this? 如何解决这个问题? Don't use long[] in the first place? 首先不要使用long []?

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) (注意可迭代类型不同)

eg 例如

Long l = 1l;

but not 但不是

Long[] ls = new long[]{1l}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM