1) The parameter of a method in Jdk5 can be defined as a variable parameter, the number of arguments passed is variable
public static void Main (string[] args) {
System.out.println (Add (2,3));
System.out.println (Add (2,3,5));
}
public static int Add (int x,int ... args) {
Intsum=x;
for (inti=0;i<args.length;i++) {
sum+= Args[i];
}
Returnsum;
}
Public class Demo4 {
@Test
public void Testsum () {
SUM (1,2,3,4);
int arr[]={5,6,7};
SUM (arr);
}
public void sum (int ... nums) {
Variable parameters as arrays
int sum=0;
for (int i:nums) {
Sum+=i;
}
SYSTEM.OUT.PRINTLN (sum);
}
Problems with variable parameter attention
public void aa (int ... nums,int s) {}//not available
public void bb (int s, int ... nums)//CAN
@Test
public void Bb () {
public static <T>List<T> aslist (T ... a)
Listlist=arrays.aslist ("1", "2", "3");
SYSTEM.OUT.PRINTLN (list);//[1,2, 3]
stringarr[]={"1", "2", "3", "4"};
List=arrays.aslist (arr);
SYSTEM.OUT.PRINTLN (list);//[1,2, 3, 4]
int nums[]={1,2,3,4,5};
List=arrays.aslist (Nums);
SYSTEM.OUT.PRINTLN (list);//[[[email protected]]
Integer nums2[]={1,2,3,4,5};
List=arrays.aslist (NUMS2);
SYSTEM.OUT.PRINTLN (list);//[1,2, 3, 4, 5]
}
}
2) Arrays.aslist as an example to illustrate the situation of passing in different parameters (Cehkongfu:18:50 2014/7/9)
Code Demo 1
List length is 3
List List =arrays.aslist ("A", "B", "C");
List length is 1 because 1.4 syntax is considered
String[] Arr ={"A", "B", "C"};
List List = Arrays.aslist (arr);
With 1.4 and 1.5 syntax at the same time, 1.4 syntax is preferred
The reason is that there is a new feature to ensure that the previous code is not wrong, backwards compatible
Now you need to save Arr as an element in the collection
Object obj = arr;
List list2 = arrays.aslist (obj); This time only conforms to 1.5 of the syntax, does not conform to 1.4 of the syntax, no ambiguity
List list3 = arrays.aslist (New Object[]{arr}); 1.4 is preferred, so the array is disassembled
System.out.println (List3.size ());
The base data type array only conforms to the syntax of 1.5
Int[] Nums = {n/a};
List = Arrays.aslist (nums);
System.out.println (List.size ());
Code Demo 2
List List =arrays.aslist ("A", "B", "C");
String[] arr = {"A", "B"};
List List = Arrays.aslist (arr); In accordance with the 1.4 syntax, the elements of the array are taken out into the collection according to the 5.0 syntax, and the array is stored directly into the collection
When the version is ambiguous, the virtual opportunity takes precedence over the lower version of Backwards compatibility
List List1 = Arrays.aslist ((Object) arr);
List List1 = arrays.aslist (New Object[]{arr});
SYSTEM.OUT.PRINTLN (list);
System.out.println (List1.size ());
Int[] Nums = {1,2,3,4};
List list3 = arrays.aslist (nums); Only conforms to the syntax of 1.5
System.out.println (List3.size ());
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Variable parameters of Java