zoukankan      html  css  js  c++  java
  • Java_可变参数类型

    Java方法中的可变参数类型,也称为不定参数类型,是一个非常重要的概念

    举栗子

    public class TestVarArgus {
    	public static void dealArray(int... intArray) {
    		for (int i : intArray)
    			System.out.print(i + " ");
     
    		System.out.println();
    	}
     
    	public static void main(String args[]) {
    		dealArray();
    		dealArray(1);
    		dealArray(1, 2, 3);
    	}
    }
    
    输出:
    
    1   
    1 2 3  
    

    类似数组?

    和数组很像,其实就是。编译器会在悄悄地把这最后一个形参转化为一个数组形参,并在编译出的class文件里作上一个记号,表明这是个实参个数可变的方法

    dealArray();//dealArray(int[] intArray{}); 
    dealArray(1);//dealArray(int[] intArray{1}); 
    dealArray(1,2,3);//dealArray(int[] intArray{1, 2, 3}); 
    

    和数组方法在一起无法重载。说明参数类型一致。

    public static void dealArray(int... intArray) {
    	
    }
     
    public static void dealArray(int[] intArray) {
    	// 会有Duplicate method dealArray(int[]) in type TestVarArgus的错误
    }
    

    互相兼容吗?

    public static void dealArray(int... intArray) {
    	for (int i : intArray)
    		System.out.print(i + " ");
    	System.out.println();
    }
    
    调用:
    int[] intArray = { 1, 2, 3 };
    dealArray(intArray);// 通过编译,正常运行
    
    public static void dealArray(int[] intArray) {
    	for (int i : intArray)
    		System.out.print(i + " ");
    	System.out.println();
    }
    调用:
    dealArray(1, 2, 3);// 编译错误
    
    可变参数是兼容数组类参数的,但是数组类参数却无法兼容可变参数

    只能放在最后一项

    public static void dealArray(int count, int... intArray) {
     
    }
    
    public static void dealArray(int... intArray, int count) {
    	// 编译报错,可变参数类型应该作为参数列表的最后一项
    
    }
    

    优先级

    public class TestVarArgus {
    	public static void dealArray(int... intArray) {
    		System.out.println("1");
    	}
     
    	public static void dealArray(int count, int count2) {
    		System.out.println("2");
    	}
     
    	public static void main(String args[]) {
    		dealArray(1, 2);
    	}
    }
    

    你觉得会执行哪一个方法???
    会输出2,能匹配定长的方法,那么优先匹配该方法。含有不定参数的那个重载方法是最后被选中的

  • 相关阅读:
    锂电池充电!
    触电
    记录一次调试过程中烧毁电脑主板的经历!
    如何计算一个CPU的MIPS
    铜线的载流能力问题。
    用格西烽火串口助手制作程控命令协议!
    从qt编程看内存分区。
    贴片LED用法
    RtlWerpReportException failed with status code :-1073741823. Will try to launch the process directly
    uboot学习——基于S3C2440的u-boot-1.1.6分析(一)
  • 原文地址:https://www.cnblogs.com/AganRun/p/11816060.html
Copyright © 2011-2022 走看看