devxlogo

The Comparable Interface: [java.util.Comparable]

The Comparable Interface: [java.util.Comparable]

This interface defines the way in which objects are to be compared. Anobject that implements this can be sorted as easily as any primitive, such asthe [String] class…

 import java.util.*;import java.awt.*;class SortStringArguments			// Sorts the arguments in args.{	public static void main(String[] args)	{		Arrays.sort(args);		for (int i=0; i

If the objects do not implement Comparable? You can modify the objects toimplement Comparable.

To make an object comparable:
1) Add Comparable to the object's implements list.
2) Make the object implement the compareTo() method.

The compareTo() method compares the an object with another of the same type.If the object is to come before the other, compareTo() should return anegative number. If the object should appear after the other object,compareTo() should return a positive number. Zero should be returned if theobjects are equal in the comparison.

Point is an AWT class that is not comparable. This example sorts based ondistance from the origin (0, 0):

 import java.util.*;import java.awt.*;class MyPoint extends java.awt.Point implements Comparable{	MyPoint(int x, int y)	{		super(x, y);			// Superimpose on the original (x, y) kinda like a union	}	public int compareTo(Object o)	// compareTo() is supposed to take an objectparameter	{		MyPoint p = (MyPoint)o;		double d1 = Math.sqrt(x*x + y*y);		// Frankly, it is safe to skip theMath.sqrt but it is done		double d2 = Math.sqrt(p.x*p.x + p.y*p.y);	// for the sake of the concept		if (d1 

devx-admin

Share the Post: