Add array elements in Arraylist and print values

Asked

Viewed 2,763 times

-1

I have two questions about ArrayList:

  1. Is there any way I can start the values without having to use the .add every time? For example, the normal vector uses int vetor[5]={1,2,3,4,15} and puts the values inside the brackets. In the ArrayList I have to use:

    vetor.add(1);
    vetor.add(2);
    etc...
    
  2. How do I print all values of a ArrayList? In the vector it is used loop of repetition, I did not get it in the ArrayList.

  • All answers gave landing options of how to do the initialization of an Arraylist already with elements but none gave the answer to the user’s question, which is no, it is not possible to start Arraylist directly with values like a common array.

  • @Articunol Really, I (and others too, by the way) focused so much on "how to do" that I didn’t pay attention to this detail. I updated my answer with this information :-)

4 answers

3

In Java it is not possible to initialize a List in the same way as an array, using the syntax int v[] = {1, 2, 3}. There is even a proposal for language to have this resource, but for now the only way is to use native API methods (listed below and in the other responses).

Create the list

You can pass the values directly to the method java.util.Arrays.asList:

List<Integer> lista = Arrays.asList(1, 2, 3, 4, 15);

If you already have an array of java.lang.Integer with the values, it is also possible to pass it directly, as has been said in the other answers:

Integer v[] = { 1, 2, 3, 4, 15 };
List<Integer> lista = Arrays.asList(v);

But attention, if the array is int (and not of Integer), That’s not gonna work:

int v[] = { 1, 2, 3, 4, 15 };
List<Integer> lista = Arrays.asList(v);

Actually the above code doesn’t even compile. This is because, when asList is called with an array of int (and not of Integer), the return is a List<int[]> (a list of arrays of int, that is, a list in which each element is an array), as already explained in this answer. And as I’m attributing the return of asList in a List<Integer>, the code does not compile.

In this case, the way is to do good old loop, adding the values one by one:

int v[] = { 1, 2, 3, 4, 15 };
List<Integer> lista = new ArrayList<Integer>();
for (int i : v) {
    lista.add(i);
}

From Java 8 it is also possible to use streams:

int v[] = { 1, 2, 3, 4, 15 };
List<Integer> lista = Arrays
    // cria o stream
    .stream(v)
    // convert int para Integer
    .boxed()
    // transforma em uma List
    .collect(Collectors.toList());

First I use the method stream, that by receiving a int[], will return a java.util.stream.IntStream. The following is the method boxed converts each int for their respective Integer. And finally, the method collect gets a collector. In the case, java.util.stream.Collectors.toList() causes the stream is "collected" to a list, resulting in a List<Integer>.


From the Java 9 it is also possible to use java.util.List.of:

// List.of() disponível no Java >= 9
List<Integer> lista = List.of(1, 2, 3, 4, 15);

The same observations of Arrays.asList also apply: if you pass an array of int as a parameter, the return will be a List<int[]>, then it only works if you pass an array of Integer.

The difference is that List.of returns an immutable list, while Arrays.asList nay:

// List.of() retorna lista imutável
List<Integer> lista = List.of(1, 2, 3, 4, 15);
// se tentar modificar elementos, lança java.lang.UnsupportedOperationException
lista.set(0, 9);

// Arrays.asList() retorna lista mutável
List<Integer> lista = Arrays.asList(1, 2, 3, 4, 15);
// posso modificar elementos sem problemas
lista.set(0, 9);

There are other differences listed in this answer.

Print the list

The easiest way is to simply print the entire list:

System.out.println(lista);

This prints all your elements at once:

[1, 2, 3, 4, 15]

But if you want to print one at a time, without the commas and brackets etc, make a for:

for (Integer i : lista) {
    System.out.println(i);
}

In this case, you will print one per line:

1
2
3
4
15

  • Based on the linked response, then the List.of will duplicate the memory used when compared to the Arrays.asList?

  • 1

    @Jeffersonquesado From what I saw in the JDK source code, Arrays.asList maintains the reference to the original array, while List.of creates a copy of the array.

  • 1

    @Jeffersonquesado It actually seems to be more complicated. If you have up to 2 elements, List.of only keeps references, but if there are 3 or more, there the array is copied

  • 1

    List1 and List2 contains, respectively, 1 and 2 memory positions, then continues to use the "duplicate memory" when referring to the content. But it is interesting the fact that he works differently for these cases

2

You can create the Array in the same way

Integer[] integerArray = {1,2,3};

And then convert to ArrayList taking advantage of the library java.util.Arrays:

List<Integer> integerList = Arrays.asList(integerArray);

To print, you can use a foreach instead of a for:

  for (Integer integer: integerList) {
      System.out.println(integer);
  }

2

You can use the method addAll() of java.util.Collections. This method adds all elements in a specific collection.

Example:

 Integer vetor[]={1,2,3,4,15};

 ArrayList<Integer> myList = new ArrayList<>();

 Collections.addAll(myList, vetor);

To iterate over the list use the foreach

Example:

for(Integer n: myList){
    System.out.println(n);
}

See working on Codingground.

0

You can create an immutable list, but it is not possible to change it and is available from Java 9. Example:List<Integer> integers = List.of(1, 2, 3, 4);

Another way is to create an array and add to the list using an Enhanced-for. Example:

Integer[] integers = {1, 2, 3, 4};
List<Integer> integerList = new ArrayList<>();

//Enhanced-for
for(Integer value : integers){
    integerList.add(value);
}

Doing as above is possible to use the remove method. If you were to use the asList method, for example, you would not be able to remove any item from the list. Example:

List<Integer> integersList = Arrays.asList(1, 2, 3, 4);
integersList.remove(1); //Lança a exceção java.lang.UnsupportedOperationException

The number 1 in the remove method corresponds to the index in the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.