How can I create a Java method that accepts a variable number of arguments?

前端 未结 7 702
野的像风
野的像风 2020-11-28 07:51

For example, Java\'s own String.format() supports a variable number of arguments.

String.format(\"Hello %s! ABC %d!\", \"World\", 123);
//=>          


        
7条回答
  •  清酒与你
    2020-11-28 08:29

    Take a look at the Java guide on varargs.

    You can create a method as shown below. Simply call System.out.printf instead of System.out.println(String.format(....

    public static void print(String format, Object... args) {
        System.out.printf(format, args);
    }
    

    Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:

    import static java.lang.System.out;
    
    out.printf("Numer of apples: %d", 10);
    

提交回复
热议问题