-1

I have tried to use Arrays.asList() method on a character array,something like below,

char[] array = "programming".toCharArray();
for (Character li : Arrays.asList(array)) {
  System.out.println(li);
}

But there was a compile time error. Here Array.asList is returning me a Array of character arrays like below

for (char[] li : Arrays.asList(array)) {
    System.out.println(li);
}

What i know is, Arrays.asList() method converts each element of the array into an element in List . But whats going on here? can anybody help me in understanding this ?

Pratik
  • 944
  • 4
  • 20
ravinder reddy
  • 309
  • 1
  • 4
  • 17

1 Answers1

1

Arrays.asList() converts each reference type element to an element in the list. So if you pass an array of primitives, you'll get a list that contains a single element whose type is the type of the array you passed to it.

If you pass a Character[] array instead of a char[] array, you'll get a List<Character> containing all the elements of the input array as individual elements.

The signature of Arrays.asList is - public static <T> List<T> asList(T... a). Since a generic type parameter must be a reference type, passing a primitive array is treated as if you passed a single element (whose type is the array type), which will result in a List having a single array element.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • But i get a compile time error ,when i try to do this..i am shocked to see that!! I mean ,when i do for (char li : Arrays.asList(array)) { ... } – ravinder reddy Apr 02 '15 at 11:06
  • @ravinderreddy You got a compilation error because calling `Arrays.asList` on a `char[]` productes a `List`, not a `List`. – Eran Apr 02 '15 at 11:08