Generic java class that stores comparable

I have a generic java class that stores comparison values:

public class MyGenericStorage<T extends Comparable<T>> {
    private T value;

    public MyGenericStorage(T value) {
        this.value = value;
    }

    //... methods that use T.compareTo()
}

I also have an abstract Person class:

public abstract class Person implements Comparable<Person>

and two specific subclasses, a professor and a student:

public class Professor extends Person
public class Student extends Person

Now when I want to create MyGenericStorage, like this, I get an error:

//error: type argument Student is not within bounds of type-variable T
MyGenericStorage<Student> studStore = new MyGenericStorage<Student>(new Student());

//this works: 
MyGenericStorage<Person> persStore = new MyGenericStorage<Person>(new Student());

I think this is due to the fact that I have a fundamental problem with understanding generics. Can someone explain this to me as well as how to fix it?

EDIT:

I changed MyGenericStorage to the following:

public class MyGenericStorage<T extends Comparable<? super T>> 

and now it works. Can someone explain why?

+5
source share
3 answers

You can fix this with the following declaration for MyGenericStorage:

class MyGenericStorage<T extends Comparable<? super T>> { …

, T Comparable, T. Student Professor , (?), Person.


: " . - , ?"

, , .

? super T " T". , T Student. , Comparable " "

Student extends Person, Comparable<Person>. , Comparable " ".

Java Generics, - FAQ. wild-cards.

+6

, Person extends Comparable<Person>, , Student Person , , Comparable<Person> not Comparable<Student>.

<T extends Comparable<T>>, . .

+5
public class MyGenericStorage<T extends Comparable<T>>

, , , , . , , Person Comparable<Student> Comparable<Professor>. .

+1

All Articles