SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arraylists
Exercise:
Exercises
Question:17 | ISBN:9780136091813 | Edition: 2

Question

Modify the Point class from Chapter 8 so that it defines a natural ordering by implementing the Comparable interface. Compare the Points by y-major order; that is, points with smaller y-coordinate values should come before those with higher y-coordinate values. Break ties by comparing x-coordinate values.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer



// Point.java (modified Point class)
public class Point implements Comparable
{
	// refer the textbook for the Point class
	
	/* implementation of the compareTo method of 
		the Comparable interface */
	public int compareTo(Point other)
	{
		if(y < other.y)
			return -1;
		else if(y > other.y)
			return 1;
		else if(x < other.x)
			return -1;
		else if(x > other.x)
			return 1;
		else
			return 0;
	}
}

// PointDemo.java
import java.util.ArrayList;
import java.util.Collections;
public class PointDemo
{
	public static void main(String[] args)
	{
		Point p1 = new Point(2, 8);
		Point p2 = new Point(7, 2);
		Point p3 = new Point(3, 4);
		Point p4 = new Point(1, 4);

		ArrayList points = new ArrayList();
		points.add(p1);
		points.add(p2);
		points.add(p3);
		points.add(p4);

		System.out.println("Points in the list before soring: "
				+ points);
		
		Collections.sort(points);
		
		System.out.println("Points in the list after soring: "
				+ points);
	}
}

Output :


Points in the list before soring: [(2, 8), (7, 2), (3, 4), (1, 4)]
Points in the list after soring: [(7, 2), (1, 4), (3, 4), (2, 8)]
0 0

Discussions

Post the discussion to improve the above solution.