当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。