Can I pass an array as arguments to a method with variable arguments in Java?

前端 未结 5 1961
我寻月下人不归
我寻月下人不归 2020-11-22 07:52

I\'d like to be able to create a function like:

class A {
  private String extraVar;
  public String myFormat(String format, Object ... args){
    return Str         


        
5条回答
  •  独厮守ぢ
    2020-11-22 08:10

    jasonmp85 is right about passing a different array to String.format. The size of an array can't be changed once constructed, so you'd have to pass a new array instead of modifying the existing one.

    Object newArgs = new Object[args.length+1];
    System.arraycopy(args, 0, newArgs, 1, args.length);
    newArgs[0] = extraVar; 
    String.format(format, extraVar, args);
    

提交回复
热议问题