Java long compareTo()及其示例

爪哇。朗,朗。compareTo()是java中的一个内置方法,用于以数字方式比较两个长对象。如果此对象等于参数对象,则此方法返回0;如果此对象的数值小于参数对象,则此方法返回小于0;如果此对象的数值大于参数对象,则此方法返回大于0的值。

null

语法:

public int compareTo(Object obj)

Parameter: 
obj - The object which is to be compared to.

返回: 该函数返回三个值:

  • 等于0: 对象等于参数对象
  • 小于0: 对象小于参数对象
  • 大于0: 对象大于参数对象

项目1: 下面的程序演示了函数的工作原理。

// Java program to demonstrate
// of java.lang.Long.compareTo() method
import java.lang.Math;
class Gfg1 {
// driver code
public static void main(String args[])
{
// when two objects are different
Long obj1 = new Long( 124 );
Long obj2 = new Long( 167 );
int compareValue = obj1.compareTo(obj2);
if (compareValue == 0 )
System.out.println( "object1 and object2 are equal" );
else if (compareValue < 0 )
System.out.println( "object1 is less than object2" );
else
System.out.println( "object1 is greater than object2" );
}
}


输出:

object1 is less than object2

项目2: 下面的程序演示了在不传递任何参数的情况下函数的工作

// Java program to demonstrate
// of java.lang.Long.compareTo() method
import java.lang.Math;
class Gfg1 {
// driver code
public static void main(String args[])
{
// when no argument is passed
Long obj1 = new Long( 124 );
Long obj2 = new Long( 167 );
int compareValue = obj1.compareTo();
if (compareValue == 0 )
System.out.println( "object1 and object2 are equal" );
else if (compareValue < 0 )
System.out.println( "object1 is less than object2" );
else
System.out.println( "object1 is greater than object2" );
}
}


输出:

prog.java:14: error: method compareTo in class Long cannot be applied to given types;
      int compareValue = obj1.compareTo(); 
                             ^
  required: Long
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

方案3: 下面的程序演示了在参数中传递除object以外的任何内容时函数的工作

// Java program to demonstrate
// of java.lang.Long.compareTo() method
import java.lang.Math;
class Gfg1 {
// driver code
public static void main(String args[])
{
// when anything other than object
// argument is passed
Long obj1 = new Long( 124 );
int compareValue = obj1.compareTo( "gfg" );
if (compareValue == 0 )
System.out.println( "object1 and object2 are equal" );
else if (compareValue < 0 )
System.out.println( "object1 is less than object2" );
else
System.out.println( "object1 is greater than object2" );
}
}


输出:

prog.java:14: error: incompatible types: String cannot be converted to Long
      int compareValue = obj1.compareTo("gfg"); 
                                        ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享