Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

java - Why does this class behave differently when I don't supply a generic type?

I don't understand why this confuses the compiler. I'm using the generic type T to hold an object that's not related to the put and get methods. I always thought GenericClass and GenericClass<Object> were functionally identical, but I must be mistaken. When compiling the DoesntWork class I get incompatible types - required: String - found: Object. The Works class does what I expect. What's going on here?

public class GenericClass<T> {
    public <V> void put(Class<V> key, V value) {
        // put into map
    }

    public <V> V get(Class<V> key) {
        // get from map
        return null;
    }

    public static class DoesntWork {
        public DoesntWork() {
            GenericClass genericClass = new GenericClass();
            String s = genericClass.get(String.class);
        }
    }

    public static class Works {
        public Works() {
            GenericClass<Object> genericClass = new GenericClass<Object>();
            String s = genericClass.get(String.class);
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The thing about how raw types work -- generic types that you've left out the arguments for -- is that all generics for them and their methods are erased as well. So for a raw GenericClass, the get and put methods also lose their generics.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...