java之可变参数

1) jdk5中方法的形参可以定义为可变参数,传入实参个数可变

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){

                   //可变参数当成数组

                   int sum=0;

                   for(int i:nums){

                            sum+=i;

                   }

                   System.out.println(sum);                 

         }

         //可变参数注意的问题

         //public void aa(int ...nums,int s){}//不可以

         //public void bb(int s ,int ...nums)//可以

         @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);//[[I@120d62b]

                  

                   Integer nums2[]={1,2,3,4,5};

                   list=Arrays.asList(nums2);

                   System.out.println(list);//[1,2, 3, 4, 5]

                  

         }

}

 

 

2)Arrays.asList为例演示传入不同参数的情况(cehkongfu:18:50 2014/7/9)

代码演示1

// list长度为3

List list =Arrays.asList("a","b","c");

// list长度为1, 因为考虑1.4语法

String[] arr ={"a","b","c"};

List list = Arrays.asList(arr);

// 同时符合1.4和1.5的语法,此时会优先考虑1.4的语法

// 原因是有了新功能要保证以前的代码不出错,向后兼容

// 现在就需要将arr作为一个元素存入集合

Object obj = arr;

List list2 = Arrays.asList(obj);     // 此时只符合1.5的语法,不符合1.4的语法,没有歧义

 

List list3 = Arrays.asList(new Object[]{arr});        // 优先考虑1.4,所以数组会拆开

//System.out.println(list3.size());

// 基本数据类型数组只符合1.5的语法

int[] nums = {1,2,3};

list = Arrays.asList(nums);

System.out.println(list.size());

 

代码演示2

//List list =Arrays.asList("a","b","c");

String[] arr = {"a","b"};

List list = Arrays.asList(arr);        // 按照1.4语法理解,取出数组的元素存入集合   按照5.0的语法理解,将数组直接存入集合

// 当版本出现歧义时, 虚拟机会优先考虑 低版本的   向下兼容

 

//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); // 只符合1.5的语法

 

System.out.println(list3.size());

版权声明:本文为小平果原创文章,转载请注明:http://blog.csdn.net/i10630226

posted @ 2015-07-25 19:39  dingxiaoyue  阅读(185)  评论(0编辑  收藏  举报