Java how to add insert element at beginning of variable argument array?

user63898 :

I have a function with string list argument and I want to insert element at beginning of this string list argument so that I can pass it to other function as an argument , now when I try to follow adding ArrayList but the argArr have no such method ..

ArrayList.add(0,"foo");


private void A(String... argsArr)
{
   //insert element at beginning
   B(argArr); 
}
private void B(String... argsArr)
{
}
Andy Thomas :

If you want to use a variable arguments array, you could create a new array with the element inserted. For example, using streams:

private void a(String... argsArr) {
    String[] args2 = Stream.concat(Stream.of("foo"), Arrays.stream(args))
                           .toArray(String[]::new);
    b( args2 );
}

If you prefer, you can create a new array without streams. Here's an easy way that uses a temporary List.

private void a(String... argsArr) {
    List<String> newList = new ArrayList<>();
    newList.add("foo");
    newList.addAll(Arrays.asList(argsArr));

    b(newList.toArray(new String[newList.size()]));
}

If you don't need a variable arguments array, you could use a List<> argument. It would be good form to insert the new element into a different list. The caller may provide a non-modifiable list, or may not want its list modified.

private void a2( List<String> args ) {

    List<String> newList = new ArrayList<>( args );
    newList.add(0, "foo"); // <-- Extra O(n) time to shift elements over.

    b( newList );
}

You can improve the efficiency by a constant factor by not inserting at the beginning of an existing list.

private void a2( List<String> args ) {

    List<String> newList = new ArrayList<>( );
    newList.add("foo"); 
    newList.addAll( args );

    b( newList );
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=129576&siteId=1