Java中的 CompositeName compareTo() 方法及示例
javax.naming.CompositeName 类的compareTo()方法用于将此 CompositeName 与作为参数传递的指定对象进行比较。它返回负整数、零或正整数,因为此 CompositeName 小于、等于或大于作为参数的给定 Object。如果传递的对象为 null 或不是 CompositeName 的实例,则此方法会抛出 ClassCastException。
句法:
public int compareTo(Object obj)
参数:此方法接受obj ,它是要比较的非空对象。
返回值:此方法返回负整数、零或正整数,因为此 Name 小于、等于或大于给定 Object。
例外:
如果 obj 不是 CompositeName,则此方法抛出 ClassCastException。
下面的程序说明了 CompositeName.compareTo() 方法:
方案一:
// 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
方案二:
// 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)