Fill a array with List data with one more element
By a question that I made, I figured out that tho copy elements from one list to an array I just need to use the method toArray开发者_开发百科() for this.
But let's suppose I have a List with n objects. I want to copy then into a array sized n+1 and add into the first position another object and in the other n positions the n data of the list.
This is the way I'm doing it for now, but I'm just wondering if there is a better way for do that:
Object array[] = new Object[list.size() + 1];
Object chk = new Object();
array[0] = chk;
for(int i = 1; i < array.length; i++){
array[i] = list.get(i);
}
You could used a LinkedList and use offerFirst() and then toArray(), but I doubt it really matters.
use an iterator:
...
int i = 1;
for(Object item:list){
array[i] = item;
i++;
}
I didn't understood what you are trying to achieve with that, but if I understood the problem correctly, this is how I would do it:
List<Object> elementList = new ArrayList<Object>();
Object additionalElement = new Object();
Object array[] = null;
//[Add code to populate the List]
//Add the additional element
elementList.add(0,additionalElement);
array = elementList.toArray();
This would do the trick with the advantage of not iterating anything.
If you're looking for a way to avoid having to loop through the array and the list, I think you're out of luck. Java doesn't provide a way to do a mass copy except for ones that just use a API call that does the looping through the collection behind the scenes, hidden from view.
The only way to do this without your loop would be:
Object array[] = new Object[list.size() + 1];
Object oldValues[] = list.toArray();
Object chk = new Object();
array[0] = chk;
System.arrayCopy(oldValues, 0, array, 1, oldValues.length);
System.arrayCopy
is a bit faster than looping (not too much, but faster nevertheless), although the performance boost would probably be mitigated by the toArray
, depending on the implementation of your List.
All in all, what you have is a decent approach as long as List.get(int)
is an acceptable cost. (If it's O(n), you'll end up with O(n^2) for your operation, which is suboptimal when Frank's solution is O(n).)
精彩评论