Help with interface implementation. Suppose we have an interface

public interface Sorter<T extends Comparable<T>> { void sort(List<T> list); } 

and I want to create a class that will implement this interface using genec types. I tried this:

 public class SorterImpl<T extends Comparable<T>> implements Sorter<T > { public void sort(List<T> list){ boolean erijuht1 = true; boolean erijuht2 = true; for(int a=0; a<list.size()-1; a++){ if(list.get(a) > list.get(a+1)){ erijuht1 = false; } if(list.get(a) < list.get(a+1)){ erijuht2 = false; } } } } 

The problem is that the last class does not want to compare objects with each other. How can I implement this interface in such a way that the class is with a generic type and can compare objects?

    1 answer 1

    You cannot compare two objects in this function in this way, since it is not clear which of them is considered larger and which is smaller (and equal) . list.get() returns you an object of class T , inherited from Comparable<T> . So we can use to call all the methods of this class, and in this case, compareTo (returns 1.0 or -1) . It remains to add the code for changing places in the event that the “larger” one has a smaller index. Here's what happened:

     public class SorterImpl<T extends Comparable<T>> implements Sorter<T> { public void sort(List<T> list) { // boolean erijuht1 = true; // boolean erijuht2 = true; for (int j = 0; j < list.size() - 1; j++) for (int a = 0; a < list.size() - j - 1; a++) { if (list.get(a).compareTo(list.get(a + 1)) > 0) { // erijuht1 = false; } else { // erijuht2 = false; T temp = list.get(a + 1); list.set(a + 1, list.get(a)); list.set(a, temp); } } } //Тестируем public static void main(String[] args) { List<Integer> ar = new ArrayList<Integer>() { { add(2); add(3); add(5); add(8); add(2); } }; SorterImpl s = new SorterImpl(); s.sort(ar); for (int i = 0; i < ar.size(); i++) { System.out.print(ar.get(i).toString() + " "); } } } 

    Result:

    8 5 3 2 2

    • And why are the variables erijuht1 and erijuht2 ? - privod
    • @privod tried to minimally edit the author’s code. Commented out those lines that are not needed in this answer. Thank. - Sanek Zhitnik