當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Java.lang.Short.compareTo()用法及代碼示例



描述

這個java.lang.Short.compareTo() 方法在數值上比較兩個 Short 對象。

聲明

以下是聲明java.lang.Short.compareTo()方法

public int compareTo(Short anotherShort)

參數

anotherShort─ 這是要比較的 Short。

返回值

如果此 Short 等於參數 Short,則此方法返回值 0;如果此 Short 在數值上小於參數 Short,則返回小於 0 的值;如果此 Short 在數值上大於參數 Short,則為大於 0 的值。

異常

NA

示例

下麵的例子展示了 java.lang.Short.compareTo() 方法的用法。

package com.tutorialspoint;

import java.lang.*;

public class ShortDemo {

   public static void main(String[] args) {
   
      // create short object and assign value to it
      short val1 = 50, val2 = 200, val3 = 50;
      Short Shortval1 = new Short(val1);
      Short Shortval2 = new Short(val2);
      Short Shortval3 = new Short(val3);
    
      // returns less than 0 if this Short is less than the argument Short
      int cmp = Shortval1.compareTo(Shortval2); 
      System.out.println("" + Shortval1 + " is less than " + Shortval2 + ",
         difference = " + cmp);

      // returns 0 if this Short is equal to the argument Short
      cmp = Shortval1.compareTo(Shortval3); 
      System.out.println("" + Shortval1 + " is equal to " + Shortval3 + ",
         difference = " + cmp);

      // returns greater than if this Short is greater than the argument Short
      cmp = Shortval2.compareTo(Shortval1); 
      System.out.println("" + Shortval2 + " is more than " + Shortval1 + ",
         difference = " + cmp);
   }
}

讓我們編譯並運行上麵的程序,這將產生以下結果——

50 is less than 200, difference = -150
50 is equal to 50, difference = 0
200 is more than 50, difference = 150

相關用法


注:本文由純淨天空篩選整理自 Java.lang.Short.compareTo() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。