【问题标题】:How to pass Vector of generic class as an argument?如何将泛型类的向量作为参数传递?
【发布时间】:2022-01-24 16:57:56
【问题描述】:

我有这些类(在不同的文件中):

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

我尝试解决这个问题:

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
}

但我得到了错误:

类型Application中的getMax(Vector)方法是 不适用于参数(向量)

我错过了什么?

【问题讨论】:

  • "public static &lt;T&gt; T getMax (Vector&lt;Comparable&lt;T&gt;&gt; v){" 看起来很奇怪。我建议使用public static &lt;T extends Comparable&lt;T&gt;&gt; T getMax (Vector&lt;T&gt; v){。 --- "Vector&lt;Student&gt; v = new Vector();" - Don't use raw types。 --- Vectors 是专门为并发设计的。如果我们不需要这个,我们可以使用List

标签: java generics inheritance vector


【解决方案1】:

基本上重复@Turing85 提到的内容,但问题在于您的Application.getMax()。你不想做Vector&lt;Comparable&lt;T&gt;&gt;,你想做Vector&lt;T&gt;,然后将类型参数T定义为&lt;T extends Comparable&lt;T&gt;&gt;。这是您更正后的方法标头的样子。

public static &lt;T extends Comparable&lt;T&gt;&gt; T getMax (Vector&lt;T&gt; v)


当您说Vector&lt;Comparable&lt;T&gt;&gt; 时,您是说您想要VectorComparable。而且我的意思不是“实现 Comparable 的对象”,您实际上是在说 Vector 中唯一可接受的类型是 Comparable 类 - 它会使任何实现 Comparable 的类无效 em>。

这是我所说的一个例子。

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);

这就是为什么说&lt;T extends Comparable&lt;T&gt;&gt; 然后说Vector&lt;T&gt; 要容易得多。如果我们将 getMax() 方法头换成 I/Turing85 给你的那个,那么你的 Application 类应该会更容易工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2019-03-05
    • 2019-02-27
    • 2022-11-28
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多