0

Suppose I have a method like below:

public void setTask(String... args) {
    //...
}

How can I create a special version of the above method that has a fixed value for the first member of args like below?

(args[0] always has a fixed value and constructorArgs.length == args.length-1.)

public void setSpecialTask(String... constructorArgs) {
    setTask("SpecialTask", constructorArgs); // ERROR: 'setTask(java.lang.String...)' cannot be applied to '(java.lang.String, java.lang.String[])'
}

'setTask(java.lang.String...)' cannot be applied to '(java.lang.String, java.lang.String[])'

Mir-Ismaili
  • 13,974
  • 8
  • 82
  • 100
  • Is the block quote your error message? If yes, then you are applying a wrong parameter type by putting an array of `String` (`String[]`) rather than an arbitrary amount of `String`s. – deHaar Aug 17 '18 at 12:18

2 Answers2

1

You can either declare a new setTask(String, String...) method or you can create an array containing the additional string:

public void setSpecialTask(String... constructorArgs) {
  String[] args = new String[constructorArgs.length + 1);
  args[0] = "SpecialTask";
  System.arraycopy(constructorArgs, 0, args, 1, constructorArgs.length);

  setTask(args);
}
assylias
  • 321,522
  • 82
  • 660
  • 783
1

An array has a fixed structure. It means that you cannot expand (or reduce) its size once instantiated.
So to achieve your requirement you have to create a new array with the wished capacity.

As alternative while not the most efficient way (with small list it is fine), convert the array to List, add the missing element in and convert back it to an array :

public void setSpecialTask(String... constructorArgs) {
    String[] array = Arrays.asList("SpecialTask", constructorArgs)
                           .toArray(new String[constructorArgs.length+1]);
    setTask(array);    
}

Or both simple and efficient (doesn't require any intermediary List) in Java 8 :

String[] array = Stream.of("SpecialTask", constructorArgs)
                       .toArray(String[]::new);
setTask("SpecialTask", array); 
davidxxx
  • 125,838
  • 23
  • 214
  • 215