Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

generics

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);
        }
    }
}
like image 606
Ryan J Avatar asked Mar 31 '13 22:03

Ryan J


People also ask

Can a non generic class inherit a generic class?

Yes, in this case, inheritance is a better solution than composition as you have it, because a StackInteger is a Stack .

What is difference between class and generic class?

The generic class works with multiple data types. A normal class works with only one kind of data type.

Why do we need generic classes?

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.

What does it mean for a class to be generic?

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.


1 Answers

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.

like image 53
Louis Wasserman Avatar answered Sep 16 '22 23:09

Louis Wasserman