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 < d2)		{			return -1;			// Orig point goes/stays before the point it is compared to		}		else if (d2 < d1)		{			return 1;			// Orig point goes after the point it is compared to		}			return 0;			// Points stay put.	}}class SortPoints{	public static void main(String[] args)	{		Random rnd = new Random();		MyPoint[] points = new MyPoint[10];		for (int i=0; i
See also  How to Avoid Money Transfer Scams  

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist