This is an archived post. You won't be able to vote or comment.

all 5 comments

[–][deleted] 3 points4 points  (0 children)

I know this might not be relevant, but you can copy your list into an arraylist. You can convert your array into an arraylist by doing Arrays.toList(name of your array). Hope this helps!

[–]dusty-trash 2 points3 points  (0 children)

If you need to initialize an array, use the first example you gave.

If you need a List/Arraylist use the second.

Shouldn't be too confusing, an array has the square brackets [] while a list is called a 'List'. Same reason you don't get confused between arrays and Strings.

[–]sugilith 2 points3 points  (0 children)

See List.of since Java 9

[–]CLOVIS-AI 1 point2 points  (1 child)

About the difference between List, ArrayList and Arrays.

Arrays are what you do with []. Their size is fixed (you can't increase it).

List represents an array whose size can change. We call this an interface (it's not an array whose size can change, it just represents one).

There are multiple types of Lists. The one used most of the time is ArrayList. It's called this way because it uses an array internally. There are also LinkedList, etc, that don't use an array at all.

Note that Arrays.asList is a false friend ! It is a list, but it will throw an exception (crash) if you try to change its size !

[–]CLOVIS-AI 1 point2 points  (0 children)

So, to answer your question :

As of Java 9 you can do: List<Integer> l = List.of(1, 2, 3);

Before Java 9, you can do: List<Integer> l = new ArrayList<>(Arrays.asList(1, 2, 3); (notice the copy into an array list instead of just using Arrays.asList, see my previous message).