简体   繁体   English

Java可比接口:compareTo int属性

[英]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.valueOfcompareTo结合使用是相同的:

public int compareTo(myObject other) {
    return Integer.valueOf(this.intValue).compareTo(Integer.valueOf(other.intValue));
}

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

相关问题 Java可比接口的compareTo方法 - Java Comparable Interface compareTo method java.lang.NullPointerException:尝试在 JSoup 库上调用接口方法“int java.lang.Comparable.compareTo(java.lang.Object)” - java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.Comparable.compareTo(java.lang.Object)' on JSoup Library Java的可比较接口:处理null参数以进行compareTo() - Java's Comparable Interface: Handling null arguments to compareTo() compareTo方法(在Comparable接口中)是否是递归的? - Is the compareTo method (in the Comparable interface) recursive? 实现compareTo()和Comparable-interface - Implementing compareTo() and Comparable-interface 扩展可比较的界面和覆盖compareTo - Extending comparable interface and override compareTo 在 Comparable 接口中覆盖 compareTo() 的问题 - Problems with overriding compareTo() in interface Comparable Java Generics Comparable | 实现compareTo - Java Generics Comparable | implement compareTo Java Comparable - 自定义 compareTo 结果 - Java Comparable - custom compareTo consequences Java 11中的CharSequence接口添加了方法`compare`。为什么不比较可比接口的`compareTo`? - CharSequence interface in Java 11 added method `compare`. Why not `compareTo` of Comparable interface?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM