0

I am new to java and reading a tutorial that instructs me to use a string-cast to assign a value from LinkedList to a String object.

List l1 = new LinkedList();
l1.add("Michael");
String s1 = (String) l1.get(0);

But I did a type test and l1.get(0) reported as a String type:

System.out.println(l1.get(0).getClass());

Result: 
class java.lang.String

So I don't understand why the result of l1.get(0) has a type of String but I still need to type-cast it as a String in order to assign same to String variable.

okey_on
  • 2,888
  • 8
  • 28
  • 36
  • the runtime knows, the compiler doesnt! – x4rf41 Sep 17 '15 at 02:50
  • Because you did not specify any type when declaring your list thus the compiler have no idea which types reside in your list hence forcing you to manually cast them at retrieval. Declare your list as follow : `List l1 = new LinkedList<>();` and you won't have to specify cast anymore as it will be done automatically. You might want to read about generics for a better understanding. – Jean-François Savard Sep 17 '15 at 02:52
  • the java compiler requires the cast because of this: https://en.wikipedia.org/wiki/Type_safety#Java – x4rf41 Sep 17 '15 at 02:52
  • 1
    @SotiriosDelimanolis I don't think that this is the OP's issue - it looks like he doesn't understand the difference between static and actual types in Java. Need to find a more helpful duplicate. – Erwin Bolwidt Sep 17 '15 at 02:55
  • the questing was `I don't understand why the result of l1.get(0) has a type of String but I still need to type-cast it` and the answer is Type Safety. i think the duplicate explains that pretty well – x4rf41 Sep 17 '15 at 03:00

0 Answers0