Java接口比较器静态比较 [英] Java Interface Comparator static compare

查看:101
本文介绍了Java接口比较器静态比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int compare(Object o1,Object o2)
比较其两个参数的顺序。

int compare(Object o1, Object o2) Compares its two arguments for order.

要比较2个对象o1和o2,需要执行以下操作:

For compare 2 objects o1 and o2 need do something like:

MyClass o1=new MyClass();
MyClass o2=new MyClass();

 if (o1.compare(o1,o2)>0) ......

为什么此方法不是静态的?
如果方法是静态的,例如:

Why this methtod not static? If method was static possible like:

 if (MyClass.compare(o1,o2)>0) ....


推荐答案

如果是静态的,怎么可能被多态地称为? 比较器的意义在于,您可以将 instance 传递给类似 sort 之类的东西。 。,则必须在比较器实例上调用比较方法

If it were static, how could it be called polymorphically? The point of Comparator is that you can pass an instance into something like sort... which has to then call the compare method on the comparator instance.

如果一个类能够比较一个自身实例到另一个,它应该实现 Comparable ,所以您应该这样写:

If a class is capable of comparing one instance of itself to another, it should implement Comparable instead, so you'd write:

if (o1.compareTo(o2))

这篇关于Java接口比较器静态比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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