How to add arguments to varargs? [duplicate]

那年仲夏 提交于 2019-12-10 03:34:20

问题


Suppose I have methods

void m1(Object... objs) {
   m2("added", objs);
}

and

void m2(Object... objs) {
   for (Object o : objs) {
      // do something with Object o
   }
}

If I call m1("a", "b"), I'd like m2 to see an array of 3 Objects (Strings "added", "a" and "b"). However, instead m2 sees just 2 objects: String "added" and an Object[] array, which internally contains Strings "a" and "b".

How can I get the desired behavior, that is, I simply add elements to the varargs before forwarding them to another method?


回答1:


You can write a method like this:

public static Object[] merge(Object o, Object... arr) {
    Object[] newArray = new Object[arr.length + 1];
    newArray[0] = o;
    System.arraycopy(arr, 0, newArray, 1, arr.length);

    return newArray;
}

and, subsequently:

m2(merge("added", objs));



回答2:


Use a List, add your new element, add the elements from the varagrs array, then transform the List back to an array.

void m1(Object... objs) {
    List<Object> list = new ArrayList<>();
    list.add("added");
    list.addAll(Arrays.asList(objs));
    m2(list.toArray());
}

With a LinkedList you could call addFirst().




回答3:


Varargs is functionally the same as passing in an array, except that the user is not required to construct the array. As per the docs, "the final argument may be passe as an array or as a sequence of arguments" (original italics). As such, if passed as a sequence of arguments, the array is constructed from the variable arguments passed in.

In your case, you want to add something to that array... so you have to create a new array:

void m1(Object... objs){
  Object[] newObjs = new Object[objs.length + 1];
  newObjs[0] = "added";
  System.arraycopy(objs, 0, newObjs, 1, objs.length);
  m2(newObjs);
}


来源:https://stackoverflow.com/questions/18475232/how-to-add-arguments-to-varargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!