Search code examples
javaarraysvariadic-functions

Create an Array from existing array with additional element added


I have a method that takes a vararg Array of strings

void count(long delta, String... tags);

I have a predefined array of tags for the most cases

String[] tags = { "foo_tag:Foo",
                  "bar_tag:Bar",
                  "baz_tag:Baz"
                };

and only one tag to be added to predefined tags in each call "project_id:12345"

So the call of count should look like this:

count(delta, "foo_tag:Foo", "bar_tag:Bar", "baz_tag:Baz", "project_id:12345");

How can I simply create a new array containing my existing one plus additional element just in place of calling the method?

Something like this hypothetical Arrays.append method:

count(delta, Arrays.append(tags, "project_id:12345"));

This is storing statistics operation, not business logic, so I want this operation to be as fast as possible.
Currently, I have a helper method appendTag, but it doesn't look elegant to me

private String[] appendTag(String[] tags, String s)
{
    String[] result = new String[tags.length + 1];
    System.arraycopy(tags, 0, result, 0, tags.length);
    result[result.length-1] = s;
    return result;
}

Solution

  • In java, arrays have a fixed size so it won't be possible to extend an array by appending new elements to it.

    You will need to create a new array with a larger size and copy the first one elements into it, then add new elements to it, but it's not dynamic yet.

    What I can suggest is to use a Collection maybe an ArrayList you will profit from its built-in methods like .add()