Export (0) Print
Expand All

Comparator.compare Method

Visual Studio 2005

Compares two objects for relative order.

Package: java.util

Assembly: vjslib (in vjslib.dll)


public abstract int compare(
    java.lang.Object o1,
    java.lang.Object o2);

Parameters

o1

The first object to be compared.

o2

The second object to be compared.

Negative value if o1 is less than o2.

Zero if o1 and o2 are equal.

Positive value if o1 is greater than o2.

In this example, you compare the three strings, two strings at a time. You get three different results for three comparisons.

// comp-comp1.jsl
// Comparator.compare example

import java.text.*;
import java.util.*;

public class Program
{
    public static void main(String[] args)
    {
        // Construct a Collator object(implements Comparator):
        Collator col = Collator.getInstance();

        // Declare some string objects:
        String s1 = "C#";
        String s2 = "J#";
        String s3 = "C#";

        // Compare strings and display the results:
        System.out.println("The comparison result for s1 & s2 = " +
                            col.compare(s1,s2));
        System.out.println("The comparison result for s2 & s1 = " +
                            col.compare(s2,s1));
        System.out.println("The comparison result for s1 & s3 = " +
                            col.compare(s1,s3));
    }
}

/*
Output:
The comparison result for s1 & s2 = -1
The comparison result for s2 & s1 = 1
The comparison result for s1 & s3 = 0
*/

Throws java.lang.ClassCastException if the types of the two objects are different or cannot be compared with this method.

Community Additions

ADD
Show:
© 2015 Microsoft