Java泛型 - 插入内部类型参数 [英] Java Generics - inserting inner type parameter

查看:111
本文介绍了Java泛型 - 插入内部类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是java的新手。我只是试图将 Comparable< String> 传递给泛型类型的方法参数< E extends Comparable< E>> 。我相信< E扩展Comparable< E>> 的含义是扩展 Comparable 的任何对象。请让我知道如何传递 Comparable< String> 或任何延伸 Comparable< String> 的对象,并有另一个对象。



编译器给我错误推断类型比较< String>不是有界参数的有效替代< E extends Comparable< E>< / code>< / p>

< h2>代码: b

  public class Compare< T>实现Comparable< T> {

public int compareTo(T o){

return 0; //不担心逻辑

}

}

class CompareTest {

public< E extends Comparable< E>> void testGeneric(E e){

System.out.println(Executed);
}

public static void main(String args []){
Compare< String> compare = new Compare< String>();

CompareTest test = new CompareTest();
test.testGeneric(compare);
//推断的类型比较< String>不是有界的
//参数的有效替代< E extends Comparable< E>>
}
}


解决方案

E扩展了Comparable< E> 意味着:能够与相同类型E的其他对象进行比较的类型E.
<但是你的比较类型没有资格。它不能与另一个Compare进行比较。 比较< T> 只能比较自己和 T ,而不是比较< ; T> ,因为它被声明为

  public class Compare< T>实现可比< T> 

使用此比较类型很难理解您要实现的目标。


I am new to java. I am just trying to pass Comparable<String> into a method parameter of generic type <E extends Comparable<E>> . I believe the meaning of <E extends Comparable<E>> is any object that extends Comparable. Please let me know how to pass Comparable<String> or any object that extends Comparable<String> and has an other object in it.

Compiler is giving me error The inferred type Compare<String> is not a valid substitute for the bounded parameter <E extends Comparable<E>>

Code:

public class Compare<T> implements Comparable<T>{

    public int compareTo(T o) {

        return 0; // Not worried about logic

    }

}

class CompareTest{

    public <E extends Comparable<E>>void testGeneric(E e){

        System.out.println("Executed");
    }

    public static void main(String args[]){
        Compare<String> compare = new Compare<String>();

        CompareTest test = new CompareTest();
        test.testGeneric(compare);
        //The inferred type Compare<String> is not a valid substitute for the bounded
        //parameter <E extends Comparable<E>>
    }
}

解决方案

E extends Comparable<E> means: a type E that is able to compare to other objects of the same type E.

But your Compare type doesn't qualify. It can't compare with another Compare. A Compare<T> can only compare itself to a T, and not to a Compare<T>, since it's declared as

public class Compare<T> implements Comparable<T>

It's quite hard to understand what you want to achieve with this Compare type.

这篇关于Java泛型 - 插入内部类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆