Java generics issue: Class "not within bounds of type-variable" error.

SamWN picture SamWN · Apr 1, 2012 · Viewed 11.4k times · Source

I'm working on a project for class that involves generics.

public interface Keyable <T> {public String getKey();}

public interface DataElement extends Comparable<Keyable<DataElement>>, Keyable<DataElement>, Serializable {...}
public class Course implements DataElement {...}


public interface SearchTree<K extends Comparable<Keyable<K>> & Keyable<K>> extends Serializable {...}
public class MySearchTree implements SearchTree<Course> {
...
    private class Node {
        public Course data;
        public Node left;
        public Node right;
        ...
    }
}

When trying to use the Course class within the declaration of MySearchTree, I receive a type argument error stating that "Course is not within the bounds of type-variable K". I spent a good amount of time trying to figure out what attributes Course might be lacking to make it not fit the bill, but came up empty.

Any ideas?

Answer

Tom Hawtin - tackline picture Tom Hawtin - tackline · Apr 2, 2012

In MySearchTree the K of the base type is Course. So K must "extend" Comparable<Keyable<Course>> & Keyable<Course>. But it doesn't, it extends Comparable<Keyable<DataElement>> & Keyable<DataElement>.

I guess DataElement should be generified in a similar manner to Comparable or Enum.

public interface Keyable <T> {public String getKey();}

public interface DataElement<THIS extends DataElement<THIS>> extends Comparable<Keyable<THIS>>, Keyable<THIS>, Serializable {...}
public class Course implements DataElement<Course> {...}


public interface SearchTree<K extends Comparable<Keyable<K>> & Keyable<K>> extends Serializable {...}
public class MySearchTree implements SearchTree<Course> {