1

I have these classes (in different files):

public class Student implements Comparable<Student> {
  ...
}
public class Application {
     public static <T> T getMax (Vector<Comparable<T>> v){
    }
}

I try to pull this off:

public static void main(){
    Vector<Student> v = new Vector();
    v.add(new Student());
    v.add(new Student());
    Application app = new Application();
    app.getMax(v);// <--- error is here
}

But i get the error:

The method getMax(Vector<Comparable>) in the type Application is not applicable for the arguments (Vector)

What am i missing?

  • 4
    "*`public static T getMax (Vector> v){`*" looks weird. I would suggest to use `public static > T getMax (Vector v){`. --- "*`Vector v = new Vector();`*" - [Don't use raw types](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). --- `Vector`s are specifically designed for concurrency. If we do not need this, we can use a `List` instead. – Turing85 Dec 23 '21 at 19:14

1 Answers1

0

Basically repeating what @Turing85 mentioned, but the issue is in your Application.getMax(). You do not want to do Vector<Comparable<T>>, you want to do Vector<T> and then have the type parameter T be defined as <T extends Comparable<T>>. Here is what your corrected method header should look like.

public static <T extends Comparable<T>> T getMax (Vector<T> v)


When you say Vector<Comparable<T>>, you are saying that you want a Vector of Comparable. And I don't mean "Objects that implement Comparable", you are literally saying that the only acceptable types permitted into your Vector is the Comparable class - which invalidates any classes that implement Comparable.

Here is an example of what I am saying.

Vector<Comparable<Integer>> comparables = new Vector<>();

//error - Integer is not a Comparable, it only IMPLEMENTS Comparable
comparables.add(12345);
Vector<Comparable<String>> comparables = new Vector<>();

//error - String is not a Comparable, it only IMPLEMENTS Comparable
comparables.add("abc");
Vector<Comparable<String>> comparables = new Vector<>();

Comparable<String> c =
    new Comparable<String>() {
            public int compareTo(String s) {
                return 0;
            }
        };

//OK - Comparable<String> is a Comparable, so it works
comparables.add(c);

That's why it is much easier to say <T extends Comparable<T>> and then just say Vector<T>. If we switch out the getMax() method header with the one I/Turing85 gave you, then your Application class should work easier.

davidalayachew
  • 1,279
  • 1
  • 11
  • 22