Write a Java program to demonstrate the use of an interface for sorting a list of objects
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)); } }
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]
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions