Home > Mobile >  Is it Arrays.asList ( ) method support the char[ ] array?
Is it Arrays.asList ( ) method support the char[ ] array?

Time:11-19

We can use Arrays.asList( ) method for String[ ] and Integer[ ] arrays. Can we use the char[ ] array in Arrays.asList( ) method?

Arrays.asList(75,85,95,70);
Arrays.asList("String", "Integer", "Character");

CodePudding user response:

The Java char keyword is a primitive data type. So that's why we can't simply convert it.

You can do it as below First convert char array to string then map it's chars to list

import java.util.stream.Collectors;
import java.util.List;
char[] chars = {'c','d','e', 'f','g'};
        List<Character> cahrList = String.valueOf(chars).chars().mapToObj(c -> (char) c).collect(Collectors.toList());

CodePudding user response:

You can use the Character class for char primitive data type:

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

public class TestCode {
    public static void main(String[] args) {
        List<Character> charList = Arrays.asList('c','d','e', 'f','g');
        System.out.println(charList);
    }
}

CodePudding user response:

Your question is conflating arrays with varargs arguments.

In your example:

Arrays.asList(75,85,95,70);

the 75,85,95,70 is not an Integer[] or an int[]. It is actually a sequence of int values for a varargs parameter.

What actually happens is that the int values are autoboxed to Integer values and these are then assembled into an Integer[]. (The autoboxing and array construction happens at the call site!)

The Integer[] is then passed to asList method with Integer as the inferred type parameter T.


So to answer question that you asked:

Is it Arrays.asList() method support the char[] array?

Yes and no.

On the one hand:

  List<Character> charList = Arrays.asList('a', 'b', 'c');

will compile and give you a list of characters. Note: List<Character> rather than List<char>.

One the other hand:

  char[] test = char[]{'a', 'b', 'c'};
  Arrays.asList(test);

will produced a List<char[]> with a single list element. Indeed, if you have an actual char[] (as distinct from a sequence of char parameters), then asList cannot convert that to List<Character>.

  • Related