0%

JavaSE varargs

There are several things to be remembered in this topic.

  • array = varargs?
    No. Although varargs are transformed to the form of array, they are not the same.
  • where to put varargs in a method?
    It must be the last element in a method’s parameter list, which means you can be allowed to have only one varargs parameter in the method signature.
  • what happens when you pass in values through varargs?
    • Java will create an array of length zero for you…
    • if you pass in an array, Java will use your array
    • if you pass in a list of elements from a array, Java will help you create an array
    • if you pass in nothing, Java will create an array of length zero for you
1
2
3
4
5
6
7
8
9
10
public statc void walk(int start, int... nums){
System.out.println(nums.length);
}

public static void main(String args[]){
walk(1); // 0
walk(1, 2); // 1
walk(1, 2, 3); // 2
walk(1, new int[]{4, 5}) // 2
}

Reference