Forum Stats

  • 3,760,187 Users
  • 2,251,659 Discussions
  • 7,871,017 Comments

Discussions

generic method vs wildcarded parameter?

843793
843793 Member Posts: 41,732 Green Ribbon
edited May 2, 2010 5:44PM in Generics
In the following, 'doesntCompile' doesn't compile. As you can see, it uses a wildcard in it's parameter. The method 'alsoCompiles' compiles, but uses a type variable in it's parameter. Various books I've read discuss that type variables (in generic methods) are needed to resolve issues between multiple parameters, or between a parameter and the method's return type. But in this case, there is only one parameter and the return type is void. So I don't understand why 'doesntCompile' won't compile. I'd appreciate it if someone could clarify this issue. Thanks in advance...
import java.util.Iterator;

public class Test {
	class Bar<E> {}
	
	public void m() {
		compiles((Iterator<Bar<String>>) null);
		alsoCompiles((Iterator<Bar<String>>) null);
		doesntCompile((Iterator<Bar<String>>) null);
	}
	
	public void compiles(Iterator<?> x) {}

	public <T> void alsoCompiles(Iterator<Bar<T>> x) {}	
	
	public void doesntCompile(Iterator<Bar<?>> x) {}	
}

Comments

  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    I should have mentioned, the specific compiler error occurs on line 9 and is:

    The method doesntCompile(Iterator<Test.Bar<?>>) in the type Test is not applicable for the arguments (Iterator<Test.Bar<String>>) Test.java
  • jtahlborn
    jtahlborn Member Posts: 2,040
    because Iterator<Test.Bar<?>> and Iterator<Test.Bar<String>> are not the same types (obvious answer, i know). your doesntcompile method takes an Iterator which returns a specific type "Test.Bar<?>". "Test.Bar<String>" is not this specific type, so it doesn't compile. if you want to accept an Iterator which returns some non-specific subclass of "Test.Bar", then you need to change the type to "Iterator<? extends Test.Bar<?>>". [This FAQ|http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html] is a great place to sort out all kinds of similar situations.
  • 843793
    843793 Member Posts: 41,732 Green Ribbon
    Thank you for a great explanation!
This discussion has been closed.