Reputation: 57
I am writing a file writer that generates strings in a certain format, using provided arguments. I would like the arguments to be passed to the method in the simplest way possible for the user. The arguments can be of any type, since they will use the toString() method to be turned into strings. Here's a simple example:
public String writeLine( Object arg1, Object arg2 ) {
return "(" + arg1.toString() + "," + arg2.toString() + ")";
}
However, I need to be able to pass a potentially unlimited amount of arguments (arg3, arg4, etc.). What is the best way to do this? I thought of doing this:
public String writeLine( Object[] argArray ) {
String str = new String();
for (int i = 0; i < argArray.length; i++) {
str += argArray[i].toString();
}
return str;
}
public static void main(String[] args) {
float[] values = {0.1, 0.2, 0.4, 0.8};
writeLine( values ); //<------ Compile Error
}
But I quickly realized that this does not work if I want to pass specific types of arrays. The float array would need to be converted to an Object array first, which would be unnecessary work on the user's part. What is the best way to simplify this?
Upvotes: 0
Views: 837
Reputation: 246
try:
public String writeLine( Object... args ) {
...
}
When using primitive arrays, make sure to replace them with an array of the appropriate wrapper type, e.g.
Float[] values = {0.1f, 0.2f, 0.4f, 0.8f};
Upvotes: 4
Reputation: 198211
You have to special-case all primitive array types -- e.g. float[]
, int[]
-- but for object types you can just have a single method that takes an Object[]
.
Upvotes: 3