Search code examples
javacollectionsexceptiontreeset

Unhandled exception java.lang.ClassCastException: java.util.TreeMap cannot be cast


I am trying to wrap a hashmap into another class, but I keep getting this

Unhandled exception java.lang.ClassCastException: java.util.TreeMap cannot be cast

It is pretty simple, not sure why Java is complaining. Here's the wrapper:

public class ResponseHeader extends HashMap<String, String> {
}

and here is the cast

protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
    try {
        // Save http headers
        mResponseHeaders = (ResponseHeader)response.headers;

the response.headers is defined as such:

public final Map<String, String> headers;

I looked into this thread, but it is not what I seek.

Why does TreeSet throws ClassCastException

any explanations? thank you!

added, I forgot

private ResponseHeader mResponseHeaders = new ResponseHeader();

Solution

  • Instance field headers is defined as

    public final Map<String, String> headers;
    

    You cannot make any further assumptions as to the type of headers than that it's a Map; the implementation of NetworkResponse is free to decide whatever implementation to use as long as it implements java.util.Map - it could use different implementations depending on the circumstances, or a different one in the next version of the library, etc.

    But as you can see from the exception, in actual fact, at this moment, NetworkResponse is using java.util.TreeMap as the implementation for headers.

    You're trying to cast it to ResponseHeader, which is a subclass of HashMap (but that doesn't matter, it wouldn't work even if headers was a HashMap, because you're trying to cast to ResponseHeader.

    This is simply not the correct type of the object referenced by the instance field headers. It is not clear from your question why you assume that it should be possible to cast headers to ResponseHeaders, but it's just not possible.

    You're saying that you're trying to "wrap HashMap into another class". In actuality, you're extending HashMap, not wrapping it. If you extend a class, you create a new type, which is not equal to the type that you extended. Maybe you're trying to add functionality to Map that you would like. There are better ways to do that. (Wrapping is one of them)