Sort two object using Comparable

Sort two object using Comparable

Answer: Below is sample java code where sorting has been done on Object of same class with array of Object using comparable interface:

package com.javahonk.algorithms;

import java.util.Arrays;

public class ComparableExample implements Comparable<ComparableExample> {

	static Boolean ascending = false;

	String fruits;

	public String getFruitName() {
		return fruits;
	}

	public void setFruitName(String fruitName) {
		this.fruits = fruitName;
	}

	ComparableExample(String fruitName) {
		this.fruits = fruitName;
	}

	public static void main(String[] args) {

	ComparableExample[] comparableTests = new ComparableExample[3];
	comparableTests[0] = new ComparableExample("Grape");
	comparableTests[1] = new ComparableExample("Apple");
	comparableTests[2] = new ComparableExample("Banana");

	// Sort in descending order
	System.out.println("Sort in descending order");
	Arrays.sort(comparableTests);
	for (ComparableExample comparableTest : comparableTests) {
		System.out.println(comparableTest.getFruitName());
	}

	// Sort in ascending order
	System.out.println("\nSort in ascending order");
	ComparableExample.ascending = true;
	Arrays.sort(comparableTests);
	for (ComparableExample comparableTest : comparableTests) {
		System.out.println(comparableTest.getFruitName());
	}

	}

	@Override
	public int compareTo(ComparableExample o) {
	if (ascending) {
		return this.getFruitName().compareTo(o.getFruitName());
	}else {
		return o.getFruitName().compareTo(this.getFruitName());
	}

	}

}

 

Output:
Sort two object using Comparable

Leave a Reply

Your email address will not be published. Required fields are marked *