如何将 List<string> 作为可选参数?
How do I make List<string> as optional parameter?
这是我正在处理的程序:
public class SESReqErrorIdAndArgs {
public String errorIdentifier;
public List<String> args = new ArrayList<>();
public SESReqErrorIdAndArgs(String errorIdentifier,List<String> arguments = new ArrayList<>()){
this.errorIdentifier = errorIdentifier;
this.args = arguments;
}
}
当我调用方法时,我想将第二个参数设为可选。我什至不想将其作为 null 传递。我初始化参数(第二个参数)的方式是错误的。这样做的正确方法是什么。
Java 不支持可选参数。您可以提供具有不同参数的多个签名,如下所示:
public SESReqErrorIdAndArgs(String errorIdentifier, List<String> arguments) {
this.errorIdentifier = errorIdentifier;
this.args = arguments;
}
public SESReqErrorIdAndArgs(String errorIdentifier) {
this(errorIdentifier, new ArrayList<>());
}
请注意 (1) 在 args
初始值设定项中分配 new ArrayList<>()
没有意义,因为它总是会立即被丢弃,并且 (2) 通常最好制作一个防御性副本以这种方式传递的项目数,所以这可能更好(因为 Java 10):
public SESReqErrorIdAndArgs(String errorIdentifier, List<String> arguments) {
this.errorIdentifier = errorIdentifier;
this.args = List.copyOf(arguments);
}
public SESReqErrorIdAndArgs(String errorIdentifier) {
this(errorIdentifier, Collections.emptyList());
}
最后,根据您的用例,varargs 可能 是更好的选择:
public SESReqErrorIdAndArgs(String errorIdentifier, String... arguments) {
this.errorIdentifier = errorIdentifier;
this.args = List.of(arguments);
}
这是我正在处理的程序:
public class SESReqErrorIdAndArgs {
public String errorIdentifier;
public List<String> args = new ArrayList<>();
public SESReqErrorIdAndArgs(String errorIdentifier,List<String> arguments = new ArrayList<>()){
this.errorIdentifier = errorIdentifier;
this.args = arguments;
}
}
当我调用方法时,我想将第二个参数设为可选。我什至不想将其作为 null 传递。我初始化参数(第二个参数)的方式是错误的。这样做的正确方法是什么。
Java 不支持可选参数。您可以提供具有不同参数的多个签名,如下所示:
public SESReqErrorIdAndArgs(String errorIdentifier, List<String> arguments) {
this.errorIdentifier = errorIdentifier;
this.args = arguments;
}
public SESReqErrorIdAndArgs(String errorIdentifier) {
this(errorIdentifier, new ArrayList<>());
}
请注意 (1) 在 args
初始值设定项中分配 new ArrayList<>()
没有意义,因为它总是会立即被丢弃,并且 (2) 通常最好制作一个防御性副本以这种方式传递的项目数,所以这可能更好(因为 Java 10):
public SESReqErrorIdAndArgs(String errorIdentifier, List<String> arguments) {
this.errorIdentifier = errorIdentifier;
this.args = List.copyOf(arguments);
}
public SESReqErrorIdAndArgs(String errorIdentifier) {
this(errorIdentifier, Collections.emptyList());
}
最后,根据您的用例,varargs 可能 是更好的选择:
public SESReqErrorIdAndArgs(String errorIdentifier, String... arguments) {
this.errorIdentifier = errorIdentifier;
this.args = List.of(arguments);
}