java.lang包的Integer類的compareTo()方法以數字方式比較兩個Integer對象,如果此Integer等於參數Integer,則返回值0;否則,返回0。如果此Integer在數值上小於參數Integer,則小於0的值;如果此Integer在數值上大於參數Integer(有符號比較),則該值大於0。
用法:
public int compareTo(Integer anotherInt) 參數: anotherInt-: the Integer to be compared. 返回: - This method returns the value 0 if this Integer is equal to the argument Integer; - a value less than 0 if this Integer is numerically less than the argument Integer; - and a value greater than 0 if this Integer is numerically greater than the argument Integer (signed comparison).
例:展示java.lang.Integer.compareTo()方法的用法。
// Java program to demonstrate working
// of java.lang.Integer.compareTo() method
import java.lang.Integer;
class Gfg {
// driver code
public static void main(String args[])
{
Integer a = new Integer(10);
Integer b = new Integer(20);
// as 10 less than 20, Output will be a value less than zero
System.out.println(a.compareTo(b));
Integer x = new Integer(30);
Integer y = new Integer(30);
// as 30 equals 30, Output will be zero
System.out.println(x.compareTo(y));
Integer w = new Integer(15);
Integer z = new Integer(8);
// as 15 is greater than 8, Output will be a value greater than zero
System.out.println(w.compareTo(z));
}
}
輸出:
-1 0 1
相關用法
- Java BigInteger compareTo()用法及代碼示例
- Java IntBuffer compareTo()用法及代碼示例
- Java YearMonth compareTo()用法及代碼示例
- Java LocalDate compareTo()用法及代碼示例
- Java CharBuffer compareTo()用法及代碼示例
- Java LocalDateTime compareTo()用法及代碼示例
- Java Instant compareTo()用法及代碼示例
- Java Float compareTo()用法及代碼示例
- Java Charset compareTo()用法及代碼示例
- Java Boolean compareTo()用法及代碼示例
- Java ChronoLocalDateTime compareTo()用法及代碼示例
- Java OffsetDateTime compareTo()用法及代碼示例
- Java ShortBuffer compareTo用法及代碼示例
- Java OffsetTime compareTo()用法及代碼示例
- Java Double.compareTo()用法及代碼示例
注:本文由純淨天空篩選整理自Niraj_Pandey大神的英文原創作品 Java Integer compareTo() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。