-2

I have this compilation error when I write the following code

Boolean[] booleans = new Boolean[]{true, false, false};
String[] strings = new String[]{"hello", "world"};
Integer[] integers = new Integer[]{1, 2, 3, 4};

// When the above instances are cast to Object[], it all works fine
Object[] booleansObj = (Object[])booleans;
Object[] stringsObj = (Object[])strings;
Object[] integersObj = (Object[])integers;

// When the above instances are cast to List<T>. String and Integer still
// works, but not for Boolean
List<String> stringsList = (List<String>)strings;
List<Integer> integersList = (List<Integer>)integers;

// this will have Cannot cast from Boolean[] to List<Boolean> error
List<Boolean> booleansList = (List<Boolean>)booleans;

My question is why Boolean[] can not cast to List?

001
  • 13,291
  • 5
  • 35
  • 66
sc30
  • 131
  • 1
  • 8

2 Answers2

2

The reason why this doesn’t work is because arrays are not lists. Casting only works when objects are in the same inheritance hierarchy. You can read more about casting at this answer.

If you want to get from some array to a list, you will need to create a new list and initialise with the array, or use Arrays.asList(array). If you want a list in which you can change the number of items contained, you will need to run a second conversion, new ArrayList(Arrays.asList(array)).

Like so:

String[] array = new String[] {"a", "b", "c"};
List<String> list = new ArrayList<>(Arrays.asList(array));
davidxxx
  • 125,838
  • 23
  • 214
  • 215
ifly6
  • 5,003
  • 2
  • 24
  • 47
  • " If you want a mutable list, you will need to run a second conversion, new ArrayList(Arrays.asList(array))." Mutable is not the most appropriate term as `Arrays.asList()` is mutable for elements contained in the backed `List`. `set(index, element)` will for example change the element. – davidxxx Feb 02 '18 at 20:19
  • Changed phrasing to: 'a list in which you can change the number of items contained' – ifly6 Feb 02 '18 at 21:17
1

No one of these three casts will compile fine.
An array is not a subclass from the List class and so cannot be downcasted into a List as you try to do.
To convert an array to a List, you can use the Arrays.asList(T... a) method that accepts a generic varargs and returns a fixed-size generic list backed by the specified array.

For example this is valid:

List<String> stringsList = Arrays.asList(strings);
List<Integer> integersList = Arrays.asList(integers);
List<Boolean> booleansList = Arrays.asList(booleans);
davidxxx
  • 125,838
  • 23
  • 214
  • 215