Easily add element to varargs list

Related searches

I have these signatures:

  public static <T, E> AsyncTask<List<T>, E> Parallel(AsyncTask<T,E> t, AsyncTask<T, E>... tasks) {
    return cb -> NeoParallel.Parallel(List.of(tasks), cb);
  }

  public static <T, E> AsyncTask<List<T>, E> Series(AsyncTask<T,E> t, AsyncTask<T, E>... tasks) {
    return cb -> NeoSeries.Series(List.of(tasks), cb);
  }

how can I easily add t to the List.of(tasks)?

This won't work because it creates an immutable list:

var listOfTasks = Arrays.asList(tasks);
listOfTasks.add(0, t);

is there a way to easily create a list that I can add to, or do it in one line?

Since this call is likely unperformant:

   listOfTasks.add(0, t);

I am looking for an alternative


There is no concise way to create the list. Probably your best option is to create a new list, add both the array elements and the new element to the list and return a unmodifiable list using Collections.unmodifiableList.

    List<T> newList = new ArrayList<>(tasks.length + 1);
    newList.addAll(Arrays.asList(tasks));
    newList.add(t);
    List<T> unmodifiableList = Collections.unmodifiableList(newList);

How to add new element to Varargs?, extra is just a String array. As such: List<String> extrasList = Arrays.asList(extra); extrasList.add(description); getObject(find_arguments,� Python Numpy : Create a Numpy Array from list, tuple or list of lists using numpy.array() What is a Structured Numpy Array and how to create and sort it in Python? Create an empty 2D Numpy Array / matrix and append rows or columns in python; Delete elements, rows or columns from a Numpy Array by index positions using numpy.delete() in Python


While a short & performant (well maybe this isn't bad at all!) solution isn't possible with the current Java API, I'll showcase a one-liner with the help of Stream(s).

return cb -> NeoSeries.Series(concat(of(t), of(tasks)).collect(toList()), cb);

This line

concat(of(t), of(tasks)).collect(toList())

expanded becomes

Stream.concat(Stream.of(t), Stream.of(tasks))
      .collect(Collectors.toList());

This is lazily computed, and will avoid temporary state.


What the other answer fail to mention is null-handling. What if the varargs array is null? Arrays.asList would throw an Exception. The same for Stream.of

For that you can write a masking method such as

private static <T, E> AsyncTask<T, E>[] maskNull(final AsyncTask<T, E>[] tasks) {
    return tasks != null ? tasks : (AsyncTask<T, E>[]) new AsyncTask[0];
}

And use it like

of(maskNull(tasks))

How to pass an ArrayList to varargs method – thispointer.com, Suppose we have a method that accepts varargs of type Integer and calculates Passing an ArrayList to method expecting vararg as parameter numpy.append () : How to append elements at the end of a Numpy Array in� At first, we only have an array of lists of strings. But thanks to type erasure and our use of varargs, we can easily add a list of numbers, which we do. As a result, we pollute the heap by mixing objects of different types. The result will yet another ClassCastException when we try to read a string from the array. Console output:


So here is what I got:

before:

var tasks = Arrays.asList(args);
tasks.add(0,t);  // throws exception 

after:

var newList = new ArrayList<>(Arrays.asList(args));
newList.add(0,t);

the problem with the first one is it creates an immutable list that will throw an exception if you try to add to it after it's first created.

Varargs in Java, Put simply, the varargs usage is safe if we use them to transfer a variable number of arguments from the caller to the method and nothing more! The idea is to convert our array into a List, then append the specified element to the end of this list and then use method List.toArray () method to returns an array containing all of the elements in our list. This is demonstrated below:


Java: Arrays should not be created for varargs parameters, "collect" should be used with "Streams" instead of "list::add". Code Smell argument; varargs is an array. Simply pass the elements directly. They will be� However, you are not sure how many arguments your method is going to accept. To address this problem, Java 1.5 introduced varargs. Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs.


Kotlin's vararg and spread operator | by Tibi Csabai, Declaring vararg param as the last one in list, in a Kotlin function, looks fun < reified @PureReifiable T> arrayOf(vararg elements: T): Array<T>. Using Guava Lists.newArrayList(): Lists.newArrayList() creates a mutable ArrayList instance containing the elements of the specified array. Algorithm: Get the Array to be converted. Create an empty List. Add the array into the List by passing it as the parameter to the Lists.newArrayList() method. Return the formed List


Your question is tagged C++ and there are nice ways (like streams) to avoid varargs completely in C++. This is a great example of why va_args can cause pain. If you have any chance at all to change the signature of foo, that's your best option. Taking a std::vector<std::string> instead of va_list would just solve your problem right there.