简体   繁体   English

Java有界类型参数

[英]Java bounded type parameters

1.I thought that Interfaces in Java don't have implementations, so how can I use my compareTo() here? 1.我以为Java中的Interfaces没有实现,所以如何在这里使用我的compareTo()?

2.As far as I knew the extends keyword can add new methods to an interface in order to be implemented later. 2.据我所知, extends关键字可以向接口添加新方法,以便以后实现。 So I don't understand what/how am I exactly extending right here ? 所以我不明白我在这里到底是什么/如何扩展?

Thanks 谢谢

public class Compare {

    // simple comparison operator < > ... works only on primitives
    // that's why we need the Comparable
    public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
        int count = 0;

        for (T e : anArray)
            if (e.compareTo(elem) > 0)
                ++count;

        return count;
    }
}
  1. Interfaces in Java don't have implementations, but you can't create an instance of an interface. Java中的接口没有实现,但是您不能创建接口的实例。 (Try it - what happens when you include new List() in your code?) You can only create an instance of a class implementing that interface, and the class is required to implement the interface's methods. (尝试一下-在代码中包含new List()时会发生什么?)您只能创建实现该接口的类的实例,并且该类是实现接口的方法所必需的。

  2. In this case, you're not extending anything at all yourself. 在这种情况下,您根本不会扩展任何内容。 You just indicate 'this method can only be used for classes T which extend/implement the Comparable<T> interface'. 您仅表示“此方法只能用于扩展/实现Comparable<T>接口的类T ”。

Actually from Java 8 onwards, Interfaces can have (default, partial) implementation, but that's an aside. 实际上,从Java 8开始,接口可以具有(默认,部分)实现,但这是一个问题。 The confusing thing here is that the keyword extends has two usages: 令人困惑的是,关键字extends有两种用法:

  1. extending the functionality of classes and, as you correctly say, by analogy the Interface class hierarchies. 扩展类的功能 ,并且如您正确地说的那样,通过扩展Interface类层次结构来扩展类。
  2. For Generic classes, Bounded Type Parameters are used for defining the bounds of a type parameter, eg List<T extends Comparable> . 对于泛型类, 有界类型参数用于定义类型参数范围 ,例如List<T extends Comparable> Using the same key word was a decision made when they introduced this, presumably to emphasise how the kind of class that is suitable for this Generic T would itself have to extend Comparable (for example). 当他们引入这个关键字时,他们决定使用相同的关键字,大概是为了强调适用于此泛型T的类本身必须如何扩展 Comparable (例如)。 As classes and interfaces in Java share the same hierarchies, it doesn't really matter which you use here (though interfaces are advisable). 由于Java中的类和接口共享相同的层次结构,因此在这里使用哪个并不重要(尽管建议使用接口)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM