CompoundName compareTo() method in Java with Examples

The compareTo() method of a javax.naming.CompoundName class is used to compare this CompoundName with the specified object passed as a parameter. It returns a negative integer, zero, or a positive integer as this CompoundName object is less than, equal to, or greater than the given Object as a parameter. If the passed object is null or not an instance of CompoundName then the ClassCastException is thrown by this method.
Syntax:
public int compareTo(Object obj)
Parameters: This method accepts obj which is the non-null object to compare against.
Return value: This method returns a negative integer, zero, or a positive integer as this Name is less than, equal to, or greater than the given Object.
Exception: This method throw ClassCastException if passed obj is not a CompoundName object.
Below programs illustrate the CompoundName.compareTo() method:
Program 1:
// 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
Program 2:
// 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
References: https://docs.oracle.com/javase/10/docs/api/javax/naming/CompoundName.html#compareTo(java.lang.Object)



