Java中的 CompoundName compareTo() 方法及示例
javax.naming.CompoundName 类的compareTo()方法用于将此 CompoundName 与作为参数传递的指定对象进行比较。它返回一个负整数、零或正整数,因为此 CompoundName 对象小于、等于或大于作为参数的给定对象。如果传递的对象为 null 或不是 CompoundName 的实例,则此方法会抛出 ClassCastException。
句法:
public int compareTo(Object obj)
参数:此方法接受obj ,它是要比较的非空对象。
返回值:此方法返回负整数、零或正整数,因为此 Name 小于、等于或大于给定 Object。
异常:如果传递的 obj 不是 CompoundName 对象,此方法将抛出ClassCastException 。
下面的程序说明了 CompoundName.compareTo() 方法:
方案一:
// Java program to demonstrate
// CompoundName.compareTo()
import java.util.Properties;
import javax.naming.CompoundName;
import javax.naming.InvalidNameException;
public class GFG {
public static void main(String[] args)
throws InvalidNameException
{
// need properties for CompoundName
Properties props = new Properties();
props.put("jndi.syntax.separator", ":");
props.put("jndi.syntax.direction",
"left_to_right");
// create compound name object
CompoundName CompoundName1
= new CompoundName("x:y:z",
props);
CompoundName CompoundName2
= new CompoundName("x:y:m",
props);
// apply compareTo()
int value
= CompoundName1
.compareTo(CompoundName2);
// print value
if (value > 0)
System.out.println(
"CompoundName1 is "
+ "greater than CompoundName2");
else if (value < 0)
System.out.println(
"CompoundName1 is "
+ "smaller than CompoundName2");
else
System.out.println(
"CompoundName1 is "
+ "equal to CompoundName2");
}
}
输出:
CompoundName1 is greater than CompoundName2
方案二:
// Java program to demonstrate
// CompoundName.compareTo() method
import java.util.Properties;
import javax.naming.CompoundName;
import javax.naming.InvalidNameException;
public class GFG {
public static void main(String[] args)
throws InvalidNameException
{
// need properties for CompoundName
Properties props = new Properties();
props.put("jndi.syntax.separator", "@");
props.put("jndi.syntax.direction",
"left_to_right");
// create compound name object
CompoundName CompoundName1
= new CompoundName(
"x@y@z@M@n",
props);
CompoundName CompoundName2
= new CompoundName(
"x@y@z@M@n",
props);
// apply compareTo()
int value
= CompoundName1
.compareTo(CompoundName2);
// print value
if (value > 0)
System.out.println(
"CompoundName1 is "
+ "greater than CompoundName2");
else if (value < 0)
System.out.println(
"CompoundName1 is "
+ "smaller than CompoundName2");
else
System.out.println(
"CompoundName1 is "
+ "equal to CompoundName2");
}
}
输出:
CompoundName1 is equal to CompoundName2
参考:https://docs.oracle.com/javase/10/docs/api/javax/naming/CompoundName.html#compareTo(Java.lang.Object)