[英]Java Comparable interface: compareTo int attributes
Two objects of the same type each have int attributes called intValue. 相同类型的两个对象均具有称为intValue的int属性。 How can the Comparable interface be used to compare these two objects on the basis of their intValue int values? 如何使用Comparable接口基于它们的intValue int值比较这两个对象?
public int compareTo(myObject other) {
return (this.intValue).compareTo(other.intValue);
}
firstObject.compareTo(secondObject);
This produces the error 这会产生错误
error: int cannot be dereferenced
First make sure that your myObject
class implements the Comparable
interface: 首先确保您的myObject
类实现了Comparable
接口:
public class myObject implements Comparable<myObject>
If you're deducing the value returned by compareTo
using primitive int
values, you could use the Integer.compare
method: 如果要使用原始int
值推导出compareTo
返回的值,则可以使用Integer.compare
方法:
public int compareTo(myObject other) {
return Integer.compare(this.intValue, other.intValue);
}
This is logically the same as using Integer.valueOf
in conjuction with compareTo
: 从逻辑Integer.valueOf
,这与将Integer.valueOf
与compareTo
结合使用是相同的:
public int compareTo(myObject other) {
return Integer.valueOf(this.intValue).compareTo(Integer.valueOf(other.intValue));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.