Is it possible to place objects in an ArrayList as soon as it is instantiated?

5

Doubt applies not only to ArrayList , but to any type of List . Is it possible to add objects to ArrayList soon after we instantiate it, and without having to use the add() method? How can this be done with arrays ?

Example of what I want to do, only using an array , instead of a collection :

int[5] array = {1, 2, 3, 4, 5};
    
asked by anonymous 05.01.2018 / 01:16

3 answers

4

Not possible in Java.

You can initialize the array to a specific size to prevent it from needing reallocations when the list gets larger than the available array .

The options quoted in response linked in comment above and other answers here generate a real list, generate something that looks like a list, but it stays immutable and can not do everything that is expected from a list. And it's not something efficient, it's just a facilitator.

If this works, then an array solves your problem and can be initialized as desired. By taking the other solutions or not solving the problem mentioned or the problem can be solved in a much more elegant and performative way.

You can create a method that creates an actual list from a sequence of arguments, but it is not efficient either. In fact it is very inefficient because there will be two copies, one to initialize the array that will be passed to the method and another to copy to the list.

In C # you can do this, but it's only syntactic sugar. In C ++ you can do it, under certain circumstances, efficiently.

    
05.01.2018 / 01:19
6

If you want a simple changeable list, nothing prevents you from doing this:

import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;

class MinhasListas {
    public static <E> List<E> of(E... elementos) {
        return new ArrayList<>(Arrays.asList(elementos));
    }
}

An example usage would look like this:

class Main {
    public static void main(String[] args) {
        List<String> x = MinhasListas.of("a", "b", "c");
        List<Integer> y = MinhasListas.of(1, 2, 3);
    }
}

And this works with any version of Java from 5 upwards. So even if you're stuck in an old version, you will have no issues.

    
05.01.2018 / 02:14
4

Starting in Java 9, you have static methods in the List for this:

List<String> abc = List.of("a", "b", "c");

However, using this method creates a list that will be immutable, and you can not do everything you can to do with a "normal" list.

    
05.01.2018 / 01:51