3

I am trying to create ArrayList of arrays with method Arrays.asList but I am struggling to achieve this goal when I have only one array to pass into the list.

List<String[]> notWithArrays = Arrays.asList(new String[] {"Slot"}); // compiler does not allow this
List<String[]> withArrays = Arrays.asList(new String[] {"Slot"},new String[] {"ts"}); // this is ok

The problem is that sometimes I have only one array to pass as argument and since it is only one iterable method asList creates List of strings out of it instead of required List<String[]>. Is there a way or method to make the list of arrays notWithArrays without having to create it manually?

Example of creating it manually:

List<String[]> withArraysManual = new ArrayList<>();
withArraysManual.add(new String[] {"Slot"});
1
  • 2
    You mean Arrays.asList(new String[][] {{"Slot"}}); ? Commented Mar 10, 2021 at 12:17

2 Answers 2

7

I think you want to create a List<String[]> using Arrays.asList, containing the string array {"Slot"}.

You can do that like this:

List<String[]> notWithArrays = Arrays.asList(new String[][] {{"Slot"}});

or you can explicitly specify the generic type parameter to asList, like this:

List<String[]> notWithArrays = Arrays.<String[]>asList(new String[] {"Slot"});
Sign up to request clarification or add additional context in comments.

1 Comment

Another way would be to use List<String[]> notWithArrays = Collections.singletonList(new String[]{"Slot"});
5

Arrays.asList has a varargs parameter, T.... The issue that you’re facing is that Java has two ways of calling a method with a vararg parameter:

  1. With multiple arguments of type T
  2. With a single argument of type T[]

In addition, Arrays.asList is generic and infers the type parameter T from the type of its arguments. If only a single argument of array type is given, interpretation (2) takes precedence.

This means that when you write Arrays.asList(new String[] {"x"}), Java interprets this as a call of form (2) with T = String.

With multiple arguments there’s no confusion: Java always interprets it as a call of form (1), and infers T to be of type String[].

So the solution, as khelwood has shown, is to disambiguate calls with a single argument, either by packing the argument into an additional array layer, or by explicitly specifying the generic type parameter T.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.