user1413969
user1413969

Reputation: 1291

Java: turning an arraylist into an array with an added element

I know that the code to turn an arraylist into an array is:

private String[] arrayLst_to_array(ArrayList<String> al) {
    String[] arr = new String[al.size()];
    arr = al.toArray(arr);
    return arr;
}

But I want my new array to have a certain string in the beginning and then after that, I want the rest of the arraylist.

I know that I could just add the string that I want to the beginning of the arraylist and then convert it, but is there a more efficient way?

Upvotes: 1

Views: 105

Answers (4)

Joni
Joni

Reputation: 111259

If you add an item to the beginning of the list, the contents of the entire list have to be moved one position up. This means each element is touched twice in the entire operation. If you export the list to an array and then use System.arrayCopy to make room for one in the beginning, again each item is touched twice.

The easiest solution that touches each item only once seems to be creating the array, adding the string, and then iterating over the list to add its elements.

String[] arr = new String[al.size() + 1];
arr[0] = someStr;
int i=1;
for (String s: al) {
    arr[i++] = s;
}

Whether this is faster than the approaches that iterate over the items twice but benefit from the efficiency of System.arrayCopy should be shown by benchmarks.

Upvotes: 1

Neet
Neet

Reputation: 4047

A memory efficient but maybe not so well performing solution would be:

public static String[] listPlusOne(final ArrayList<String> list, final String prepend)
{
    final String[] arr = list.toArray(new String[list.size() + 1]);
    System.arraycopy(arr, 0, arr, 1, list.size());
    arr[0] = prepend;
    return arr;
}

This solution allocates only one String array and performs a memory move using System.arrayCopy() to move all the elements one position up.

Generally speaking memory moving is always not the best solution. A LinkedList will allow pretty quick element prepending, but has O(n) complexity when accessing elements at random positions. The ArrayList is slower on prepending (memory moving, reallocation) but has O(1) when accessing elements.

So, either you use something like the code above, or you prepend the element to the list.

Upvotes: 1

arshajii
arshajii

Reputation: 129507

You can use System.arraycopy():

String[] arr = new String[al.size() + 1];
arr[0] = someStr;  // initial string

// copy the list:
System.arraycopy(al.toArray(), 0, arr, 1, al.size());

return arr;

Upvotes: 7

Kaushik Sivakumar
Kaushik Sivakumar

Reputation: 205

In Short Answer to your question is No.The Option you gave i believe is the best way to do it.

Upvotes: -2

Related Questions