Noah
Noah

Reputation: 57

Can an array of any java types or an Object array be passed to a method?

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?

  1. Write several methods that take common array types as arguments ( writeLine( float[] argArray ), writeLine( String[] argArray ), etc. ) (won't work for all types)
  2. Convert all arrays to Object arrays before passing (slow and extra work).
  3. Something else?

Upvotes: 0

Views: 837

Answers (2)

Kamahl
Kamahl

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

Louis Wasserman
Louis Wasserman

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

Related Questions