简体   繁体   English

Java 和 Comparable

[英]Java and Comparable

I'm new here and this is my first post.我是新来的,这是我的第一篇文章。 I've just completed my Java OCA and now moving onto studying for the OCP.我刚刚完成了我的 Java OCA,现在正在学习 OCP。 I have a question regarding Comparable interface.我有一个关于 Comparable 接口的问题。

I have this code snippet which explains how Comparable is implemented:我有这个代码片段解释了 Comparable 是如何实现的:

import java.util.*;
public class Duck implements Comparable<Duck> {
private String name;
public Duck(String name) {
this.name = name;
}
public String toString() {   // use readable output
return name;
}
public int compareTo(Duck d) {
return name.compareTo(d.name); // call String's compareTo
}
public static void main(String[] args) {
List<Duck> ducks = new ArrayList<>();
ducks.add(new Duck("Quack"));
ducks.add(new Duck("Puddles"));
Collections.sort(ducks); // sort by name
System.out.println(ducks); // [Puddles, Quack]
}
}

I more or less understand what is goin on here but below this code snippet the author quotes that:我或多或少了解这里发生了什么,但在此代码片段下方,作者引用了以下内容:

The Duck class implements the Comparable interface. Duck 类实现了 Comparable 接口。 Without implementing that interface, all we have is a method named compareTo(), but it wouldn't be a Comparable object.如果没有实现那个接口,我们只有一个名为 compareTo() 的方法,但它不会是一个 Comparable 对象。

My question is why would it not be comparable?我的问题是为什么它没有可比性? Is this something to do with the fact that calling code such as the Collections.sort() would internally use the Comparable type as a reference parameter to compare any object?这是否与调用诸如Collections.sort()代码会在内部使用 Comparable 类型作为引用参数来比较任何对象的事实有关?

Thanks in advance for any help and I hope my question makes sense.在此先感谢您的帮助,我希望我的问题有意义。

My question is why would it not be comparable?我的问题是为什么它没有可比性? Is this something to do with the fact that calling code such as the Collections.sort() would internally use the Comparable type as a reference parameter to compare any object?这是否与调用诸如 Collections.sort() 之类的代码会在内部使用 Comparable 类型作为引用参数来比较任何对象的事实有关?

I'm not sure what you exactly mean by reference parameter .我不确定您所说的引用参数究竟是什么意思。

In Java, it is not enough for a class to provide implementation for a method on an interface (or a class) to become that type.在 Java 中,一个类为接口(或类)上的方法提供实现以成为该类型是不够的。 It has to be explicitly mentioned in the class declaration.它必须在类声明中明确提及。


There are two overloaded sort utility methods on the Collection class. Collection类中有两个重载的排序实用程序方法。

public static <T extends Comparable<? super T>> void sort(List<T> list)

public static <T> void sort(List<T> list, Comparator<? super T> c)

When your class implements Comparable , you can pass just the list of objects of that class in the first method.当您的类实现Comparable ,您可以在第一个方法中只传递该类的对象列表。 If it does not implement Comparable , it will not compile as the bounds for T must extend Comparable .如果它没有实现Comparable ,它就不会编译,因为T的边界必须扩展Comparable In that case, you will be forced to pass an explicit Comparator to compare the objects.在这种情况下,您将被迫传递一个显式的Comparator来比较对象。

As the author of the book mentioned, having a method whose signature is the same as the method in an arbitrary interface (or class) does not make it of that type.正如这本书的作者所提到的,拥有一个签名与任意接口(或类)中的方法相同的方法并不能使它成为那种类型。

Duck Typing does not work in Java Duck Typing在 Java 中不起作用

Java is a Object Oriented Based language. Java 是一种基于面向对象的语言。 Which supports inheritance through classes/ polymorphism through class/abstract class/interface支持通过类继承/通过类/抽象类/接口的多态性

interface Comparable<T> {
  // methods
}

class Person implements Comparable<Person> {
//methods
}

This essentially means any object of the Type Person is also of the Comparable Type.这实质上意味着 Person 类型的任何对象也属于 Comparable 类型。

interface Runnable {}
class Task implements Runnable {}

this means any object created of Task class is also of the Runnable Type.这意味着 Task 类创建的任何对象也是 Runnable 类型。

This is what the author means.这就是作者的意思。

If you do not implement Comparable interface, yet define the compareTo() method, you are just defining a method inside the class, as any other method.如果您没有实现 Comparable 接口,但定义了 compareTo() 方法,那么您只是在类中定义了一个方法,就像任何其他方法一样。 YOU ARE NOT OVERRIDING THE compareTo() method in the Comparable interface defined.您没有覆盖定义的 Comparable 接口中的 compareTo() 方法。

You can still compare each object using your compareTo() method, but you need to define your own sort method which internally would call compareTo() method to get the list in a sorted way.您仍然可以使用 compareTo() 方法比较每个对象,但您需要定义自己的排序方法,该方法在内部将调用 compareTo() 方法以排序方式获取列表。

The Java API Collections.sort() internally converts the list to an Object[] and calls the Arrays.sort(). Java API Collections.sort() 在内部将列表转换为 Object[] 并调用 Arrays.sort()。 Now Arrays.sort() will use a modified version of the TimSort Algorithm for sorting and the contract is - it does the sorting of elements of the Array only if they are of the Comparable Type.现在 Arrays.sort() 将使用 TimSort 算法的修改版本进行排序,并且约定是 - 只有当数组元素属于可比较类型时,它才会对数组元素进行排序。

  • ComparableTimSort可比时间排序
  • Collections.sort() Collections.sort()

You can check, for all of the internal calls, it states clearly :您可以检查所有内部调用,它清楚地说明:

@throws IllegalArgumentException (optional) if the comparator is found to violate the {@link Comparator} contract @throws IllegalArgumentException (可选) 如果发现比较器违反了 {@link Comparator} 契约

So to pass any Object Types to the sort() it has to be also of the type Comparable.因此,要将任何对象类型传递给 sort(),它也必须是 Comparable 类型。 Strings/Wrappers are already of the Comparable Type.字符串/包装器已经是 Comparable 类型。 Hence you need to take care of this contract while defining your user defined objects.因此,您需要在定义用户定义的对象时注意这个契约。

"Without implementing that interface, all we have is a method named compareTo(), but it wouldn't be a Comparable object." “如果不实现该接口,我们只有一个名为 compareTo() 的方法,但它不会是一个 Comparable 对象。”

- Simply put, it means without implementing the interface, you have a Duck type object, NOT comparable type -简单地说,就是没有实现接口,你就有了一个 Duck 类型的对象,而不是可比较的类型

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

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