Java-Lexicographic Comparisons

Lexicographic Comparisons

Buffers also support lexicographic comparisons with the compareTo( ) method. This method returns an integer that is negative, zero, or positive if the buffer argument is less than, equal to or greater than, respectively, the object instance on which compareTo( ) was invoked. Like equals( ), compareTo( ) does not allow comparisons between dissimilar objects. But compareTo( ) is more strict: it will throw ClassCastException if you pass in an object of the incorrect type, whereas equals( ) would simply return false.

Comparisons are performed on the remaining elements of each buffer, in the same way as they are for equals( ), until an inequality is found or the limit of either buffer is reached. If one buffer is exhausted before an inequality is found, the shorter buffer is considered to be less than the longer buffer. Unlike equals( ), compareTo( ) is not commutative: the order matters. In this example, a result less than 0 would indicate that buffer2 is less than buffer1, and the expression would evaluate to true.


Program

1 output

Program Source

import java.nio.ByteBuffer;

public class Javaapp {

    public static void main(String[] args) {

        ByteBuffer buf1 = ByteBuffer.allocate(12);
        buf1.put(new byte[]{10,20,30,40,50});
        buf1.flip();
        ByteBuffer buf2 = ByteBuffer.allocate(12);
        buf2.put(new byte[]{10,20,30,40,78});
        buf2.flip();
        
        int v = buf1.compareTo(buf2);
        System.out.println("Comparison Result : "+v);
    }
}

Leave a Comment