2

I am new to Generics and trying to understand why this code compiles:

public Collection<Class<Subclass>> testFunction() {

    return Collections.singleton(Subclass.class);
}

And this code doesn't:

public Collection<Class<? extends SuperClass>> testFunction() {

    return Collections.singleton(Subclass.class);
}

My SubClass looks like this:

public class Subclass extends SuperClass{

}
6
  • 1
    both of them should compile fine (java 8), the given question doesn't relate to this issue Commented Dec 21, 2016 at 12:10
  • @Eran it that might depend on the Java version you're using, i.e. if the type inference works correctly Collections.singleton(Integer.class); should create a Collection<Class<? extends Number>> but if it doesn't (and older compilers had problems here) you'll get a type conflict. Commented Dec 21, 2016 at 12:14
  • @Eran On eclipse-neon, with jdk 8 it gives the following error message: Type mismatch: cannot convert from Set<Class<Integer>> to Collection<Class<? extends Number>> Commented Dec 21, 2016 at 12:14
  • 2
    @Vaibhav Eclipse has it's own compiler (eclipsec), but it works fine for mars. You can help out the compiler by providing the explicit type: Collections.<Class<? extends SuperClass>>singleton(Subclass.class); Commented Dec 21, 2016 at 12:18
  • @Vaibhav I am running eclipse-neon with JDK8 ... and I dont get that error. Could it be that you enabled the "compatibility" mode to java7 within your project/workspace preferences? Commented Dec 21, 2016 at 12:20

1 Answer 1

3

The above compiles fine with Java8:

class SuperClass { }
class Subclass extends SuperClass{ }

class Test {
  public Collection<Class<? extends SuperClass>> testFunction() {
    return Collections.singleton(Subclass.class);
  }
}

The point is: with Java 8, type inference was heavily reworked and improved.

So my guess here is: this doesn't compile for you because you are using Java 7; where simply spoken the compiler wasn't "good enough" to correctly resolve such kind of code.

Sign up to request clarification or add additional context in comments.

1 Comment

Here's the problem that I was facing. Your code compiles on java8 for me too now. Earlier eclipse didn't build the project with java8 compiler hence the error was there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.