I have a generic implementation of a Stack. An object of this Stack has the name stak and is of the type Character.
I tried
if ( ( ((String)(stak.head).equals("{")) && (str.charAt(i)=='}') ) { /* do something */}
The code compiles correctly but it gives me following error on runtime:
Exception in thread "main" java.lang.ClassCastException: java.lang.Character can
not be cast to java.lang.String
at One.main(One.java:36)
However, the following code works:
if ( ((Character)(stak.head) == '{') && (str.charAt(i)=='}') ) { /* do something */}
Can you please explain why doesn’t the character object get cast into String?
Simply because
Characteris not aString, doesn’t fall in the common hierarchy and hence doesn’t allow casting. You can try casting aListto anArrayListbecause the compiler knows that they share a common inheritance tree. Also, if you have a generic implementation of aStack, you really shouldn’t be relying on concrete types like this so I wonder what you’ve got in your code.Also,
{getting converted toCharacteris not about casting but about auto-boxing/unboxing.