Search code examples
javaarraysstringmemory-efficient

What is the most efficient way to add a string to this string array?


I have a string [] called myStrings. I can't convert it to anything else, it has to stay a string array. However, I need to add one more string to it so I wrote this method. I am sure there is a better, faster, less memory intensive way to do this but I can't see it. Can anyone provide a java api only way to solve this better than I have? I am using Java 1.7

String[] myStrings;  // this gets set to real values later in program.

public void addToMyStrings(String addMe){
    List<String> list = Arrays.asList( myStrings );
    if( list != null )
    {
        list.add( addMe);
        myStrings = list.toArray( new String[0] );
    }
}

Solution

  • You can't add an item to a List<T> returned by Arrays.asList(..):

    Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray().

    You could use a separated List that you build from the array manually or use directly just Arrays:

    String[] newStrings = Arrays.copyOf(myStrings, myStrings.length()+1);
    newStrings[myStrings.length()] = addMe;