Short類的compareTo()方法是Java中的內置方法,用於對兩個Short對象進行數值比較。
用法:
public int compareTo(Short otherShort)
參數:此方法接受強製參數otherShort,它是要比較的Short對象。
返回類型:它返回一個int值。它返回:
- 如果“ otherShort”等於“ thisShort”,則為0,
- 正值“ thisShort”小於“ otherShort”,
- 負值“ otherShort”大於“ thisShort”
下麵是Java中compareTo()方法的實現:
示例1:
// Java code to demonstrate
// Short compareTo() method
class GFG {
public static void main(String[] args)
{
// creating a Short object
Short a = new Short("4");
// creating a Short object
Short b = new Short("4");
// compareTo method in Short class
int output = a.compareTo(b);
// printing the output
System.out.println("Comparing " + a
+ " and " + b + " : "
+ output);
}
}
輸出:
Comparing 4 and 4 : 0
示例2:
// Java code to demonstrate
// Short compareTo() method
class GFG {
public static void main(String[] args)
{
// creating a Short object
Short a = new Short("4");
// creating a Short object
Short b = new Short("2");
// compareTo method in Short class
int output = a.compareTo(b);
// printing the output
System.out.println("Comparing " + a
+ " and " + b + " : "
+ output);
}
}
輸出:
Comparing 4 and 2 : 2
示例3:
// Java code to demonstrate
// Short compareTo() method
class GFG {
public static void main(String[] args)
{
// creating a Short object
Short a = new Short("2");
// creating a Short object
Short b = new Short("4");
// compareTo method in Short class
int output = a.compareTo(b);
// printing the output
System.out.println("Comparing " + a
+ " and " + b + " : "
+ output);
}
}
輸出:
Comparing 2 and 4 : -2
相關用法
- Java Shorts.indexOf(short[] array, short[] target)用法及代碼示例
- Java Shorts.indexOf(short[] array, short target)用法及代碼示例
- Java Charset compareTo()用法及代碼示例
- Java ChronoZonedDateTime compareTo()用法及代碼示例
- Java MonthDay compareTo()用法及代碼示例
- Java LocalTime compareTo()用法及代碼示例
- Java Double.compareTo()用法及代碼示例
- Java LocalDateTime compareTo()用法及代碼示例
- Java Calendar compareTo()用法及代碼示例
- Java UUID compareTo()用法及代碼示例
- Java Instant compareTo()用法及代碼示例
- Java OffsetTime compareTo()用法及代碼示例
- Java Date compareTo()用法及代碼示例
- Java Path compareTo()用法及代碼示例
- Java Boolean compareTo()用法及代碼示例
注:本文由純淨天空篩選整理自Sruti Rai大神的英文原創作品 Short compareTo() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。