0

Could someone please tell me why the code below will results in a compile time error without casting? Much appreciate your help.

List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);
Jess
  • 107
  • 8
  • 1
    What part of the compiler error message don't you understand? – user207421 Dec 07 '15 at 23:28
  • 1
    It is because by default List or ArrayList hold Object data types. This means that it can hold any Primitive Data Types within the same list such as byte, short, int, long, float, double, boolean, and char including the String Data Type which in itself is an immutable object (it is not a primitive). If you know that your List will contain nothing other than String data Type then you can declare your list like this: List list = new ArrayList();. Now you don't need to cast. – DevilsHnd - 退職した Dec 08 '15 at 01:59
  • @DevilsHnd Thanks for the explanation!! Really appreciate your help!! – Jess Dec 08 '15 at 04:32

0 Answers0