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


Java CompositeName compareTo()用法及代碼示例


javax.naming.CompositeName類的compareTo()方法用於將此CompositeName與作為參數傳遞的指定對象進行比較。當此CompositeName小於,等於或大於給定Object作為參數時,它將返回負整數,零或正整數。如果傳遞的對象為null或不是CompositeName的實例,則此方法將引發ClassCastException。

用法:

public int compareTo(Object obj)

參數:此方法接受obj,它是要與之比較的非null對象。



返回值:此方法返回負整數,零或正整數,因為此Name小於,等於或大於給定的Object。

異常:
如果obj不是CompositeName,則此方法拋出ClassCastException。

下麵的程序說明CompositeName.compareTo()方法:
程序1:

// Java program to demonstrate 
// CompositeName.compareTo() 
  
import javax.naming.CompositeName; 
import javax.naming.InvalidNameException; 
  
public class GFG { 
    public static void main(String[] args) 
        throws InvalidNameException 
    { 
  
        // create Composite name object 
        CompositeName compositeName1 
            = new CompositeName("x/y"); 
        CompositeName compositeName2 
            = new CompositeName("x/z"); 
  
        // apply compareTo() 
        int value 
            = compositeName1.compareTo(compositeName2); 
  
        // print value 
        if (value > 0) 
            System.out.println("CompositeName1 is "
                               + "greater than CompositeName2"); 
        else if (value < 0) 
            System.out.println("CompositeName1 is "
                               + "smaller than CompositeName2"); 
        else
            System.out.println("CompositeName1 is "
                               + " equal to CompositeName2"); 
    } 
}
輸出:
CompositeName1 is smaller than CompositeName2

程序2:

// Java program to demonstrate 
// CompositeName.compareTo() method 
  
import javax.naming.CompositeName; 
import javax.naming.InvalidNameException; 
  
public class GFG { 
    public static void main(String[] args) 
        throws InvalidNameException 
    { 
  
        // create Composite name object 
        CompositeName compositeName1 
            = new CompositeName("x/y/z/a"); 
        CompositeName compositeName2 
            = new CompositeName("x/y/x/a"); 
  
        // apply compareTo() 
        int value 
            = compositeName1.compareTo(compositeName2); 
  
        // print value 
        if (value > 0) 
            System.out.println("CompositeName1 is "
                               + "greater than CompositeName2"); 
        else if (value < 0) 
            System.out.println("CompositeName1 is "
                               + "smaller than CompositeName2"); 
        else
            System.out.println("CompositeName1 is "
                               + " equal to CompositeName2"); 
    } 
}
輸出:
CompositeName1 is greater than CompositeName2

參考文獻:https://docs.oracle.com/javase/10/docs/api/javax/naming/CompositeName.html#compareTo(java.lang.Object)




相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 CompositeName compareTo() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。