Interface for Sorting Objects in Java


Write a Java program to demonstrate the use of an interface for sorting a list of objects

  • The Sortable interface defines a method sort for sorting an array of type T.
  • The BubbleSort class implements the Sortable interface and provides a generic bubble sort algorithm to sort arrays of elements that implement the Comparable interface.
  • In the Main class, arrays of integers and strings are created.
  • Instances of BubbleSort are created for sorting integer and string arrays.
  • The sort method is called on these instances to sort the arrays.
  • Finally, the sorted arrays are printed to the console.

Source Code

import java.util.Arrays;
 
interface Sortable<T>
{
	void sort(T[] arr);
}
 
class BubbleSort<T extends Comparable<T>> implements Sortable<T>
{
	@Override
	public void sort(T[] arr)
	{
		int n = arr.length;
		for (int i = 0; i < n - 1; i++)
		{
			for (int j = 0; j < n - i - 1; j++)
			{
				if (arr[j].compareTo(arr[j + 1]) > 0)
				{
					T temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
		}
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		Integer[] intArray = {5, 1, 4, 2, 8};
		String[] strArray = { "cherry", "banana", "date", "apple"};
 
		System.out.println("Given Integers : " + Arrays.toString(intArray));
		System.out.println("Given Strings : " + Arrays.toString(strArray));
 
		BubbleSort<Integer> intSorter = new BubbleSort<>();
		BubbleSort<String> strSorter = new BubbleSort<>();
 
		intSorter.sort(intArray);
		strSorter.sort(strArray);
 
		System.out.println("Sorted Integers : " + Arrays.toString(intArray));
		System.out.println("Sorted Strings : " + Arrays.toString(strArray));
	}
}

Output

Given Integers : [5, 1, 4, 2, 8]
Given Strings : [cherry, banana, date, apple]
Sorted Integers : [1, 2, 4, 5, 8]
Sorted Strings : [apple, banana, cherry, date]

Example Programs