简体   繁体   中英

Java Hashtable linked list

Hi I have the following code for some reason it is throwing a type error: Expected String, Actual Object . Its a hashtable with string keys and linkedlist<string> values.

When iterating through these linkedlist I'm unable to set their values to a string variable. I've used to the getClass() method to ensure it is returning a string class which it is. I'm very confused and any help would be appreciated.

Enumeration t = Scope.keys();
String temp_string;
String temp_string2;
LinkedList temp_linkedlist;
while (t.hasMoreElements())
{
    temp_string = (String)t.nextElement();
    temp_linkedlist = (LinkedList)Scope.get(temp_string);
    for(int num=0; num<temp_linkedlist.size(); num++)
    {
        //Prints out string from linked list  
        System.out.println(temp_linkedlist.get(num).getClass());
        //throws error 
        temp_string2 = temp_linkedlist.get(num);
    }
}

When not using generics, all elements in a list are considered Object 's to the compiler.

To make your code work, whilst keeping generics out of the equation, try the following:

temp_string2 = (String)temp_linkedlist.get(num);

The reason getClass() gives you a String is because it is evaluated at runtime, not compile time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM