Search code examples
javagenericscollectionsgeneric-method

Is it possible to return raw object from generic method?


research this method from Colletions class:

@SuppressWarnings("unchecked")
    public static final <T> Set<T> emptySet() {
        return (Set<T>) EMPTY_SET;
    }

Collections.emptySet() return `Set<Object>`

This behaviour differ from generic classes. If I instantiate generic class without <T> I work with raw object.

I noticed this after method accept generic set was failed as compilation error:

public class GenericMethodRaw {
    public static void main(String [] args){
        Set set = Collections.emptySet();
        method(set); //fine
        method(Collections.emptySet());  //compilation error here
        Set<String> set1 = Collections.emptySet();//fine compilation
    }
    public static void method(Set<String> strings){}
}

compiler message:

java: method method in class GenericMethodRaw cannot be applied to given types;
  required: java.util.Set<java.lang.String>
  found: java.util.Set<java.lang.Object>
  reason: actual argument java.util.Set<java.lang.Object> cannot be converted to java.util.Set<java.lang.String> by method invocation conversion

Solution

  • Terminology wise, an object isn't raw. The type of a reference value can be. The type of the value returned by a method must be compatible with the method's return type. In the emptySet method it is because of the cast.

    In any case, the client will never see what happens in the call, all they know is that the method invocation expression has a type based on its invocation context.