java compareto long_Java long compareTo()用法及代码示例

java.lang.Long.compareTo()是java中的内置方法,该方法以数字方式比较两个Long对象。如果此对象等于自变量对象,则此方法返回0;如果此对象在数值上小于自变量对象,则返回小于0;如果此对象在数值上大于自变量对象,则返回大于0的值。

用法:

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:下面的程序演示了在参数中传递对象以外的任何东西时函数的工作方式

// 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值