-1

How to initialize a list of short elements in one line?

Something like this:

List<Short> numbers = new ArrayList<Short>(List.of(1, 2, 3, 4, 5));

But I am getting:

"Cannot resolve constructor 'ArrayList(java.util.List<E>)'"
Usama Abdulrehman
  • 1,041
  • 3
  • 11
  • 21

2 Answers2

3

The type ArrayList is declared as:

public class ArrayList<E> ... {
    public ArrayList(Collection<? extends E> c) { ... }
}

That means in your statement

List<Short> numbers = new ArrayList<>( ... );

the argument that you pass into the constructor must be of type Collection<? extends Short>. But you are passing a

List.of(1, 2, 3, 4, 5)

which is of type List<Integer>. Note that integral literals are int by default. Unfortunately, there is no short way to make them short. But you can always cast them:

List<Short> numbers = new ArrayList<>(List.of((short) 1, (short) 2, (short) 3, (short) 4, (short) 5));

This compiles fine.

Side note: Why do you need to create another list object (new ArrayList(...)) while already having one (List.of(...))?

Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
0

Use Integer.shortValue() method: Like below

  List<Short> numbers = Stream.of(1, 2, 3, 4, 5).map(value -> value.shortValue()).collect(Collectors.toList());
Pandey Amit
  • 657
  • 6
  • 19