Question

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] );
    }
}
Was it helpful?

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;

OTHER TIPS

If you absolutely have to use an Array then you could mimic what something like ArrayList does and double its size as needed. That way most inserts are very efficient (O(1)) complexity, but every once in a while you will have to do a full arraycopy of O(n) complexity.

This is bad design decision. If you need myStrings to change, then you need to declare it as a dynamic List from the beginning.

If you want to keep it as a fixed-bound array, then try to give it a size that you know will never be exceeded upon instantiation.

If you are unable to do that, you can use ArrayUtils.add(T[] array,T element)
The method copies your array and adds an item at the end. It should be faster than your algorithm, but not by much.

For all practical purposes, I wouldn't worry about performance unless I see a bottleneck. For example, if you expect your array to contain 3-4 items, there is not point in worrying about this for the moment. Premature optimization is evil. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top