Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Apr 28, 2000

The Comparable Interface: [java.util.Comparable]

This interface defines the way in which objects are to be compared. An object that implements this can be sorted as easily as any primitive, such as the [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<args.length; i++)		// Print output
		{
		      System.out.println(args[i]);
		}
	}
}

If the objects do not implement Comparable? You can modify the objects to implement 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 a negative number. If the object should appear after the other object, compareTo() should return a positive number. Zero should be returned if the objects are equal in the comparison.

Point is an AWT class that is not comparable. This example sorts based on distance 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 object
parameter
	{
		MyPoint p = (MyPoint)o;
		double d1 = Math.sqrt(x*x + y*y);		// Frankly, it is safe to skip the
Math.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<points.length; i++)
		{
			points[i] = new MyPoint(rnd.nextInt(100), rnd.nextInt(100));
		}
		Arrays.sort(points);

		for (int i=0; i<points.length; i++)
		{
			System.out.println(points[i]);	// Not sure if you can do this, but again
this is
		}							// just for illustrating the example.
	}
}
Jeremy Chen
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date