0

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);
    }
}
2
  • Could you post full statck trace of the error and specify the line in your code in which you have this error? Commented Nov 30, 2018 at 1:06
  • Besides the missing cast, for performance reasons You should not call size() and get(num) on a linked list. It is better to iterate over it. Commented Nov 30, 2018 at 3:46

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, how would i do it with generics?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.