Array of numbers defined

ArrayList<Integer>list = new ArrayList<Integer>(); list.add(10); list.add(-70); list.add(99); 

You can sort sheet values ​​in ascending order using the method from the Collections class; Collections.sort (list); - the method passes an array, runs through the elements, sorts them and returns a new sorted list - this is understandable.

What is the logic of work when sorting descending?

 Collections.sort(list,new Comparator(){ public int compare(Object o1, Object o2) { int a = ((Integer)o1).intValue(); //элемент преобразуется в Integer int b = ((Integer)o2).intValue(); //элемент преобразуется в Integer return a < b ? 1 : a == b ? 0 : -1; //выполняется сравнение и возврат наименьшего элемента } }); 

It is not clear how an anonymous class works? How are items from list taken and passed as parameters to the compare () method?

  • one
    You have already looked at how Collections.sort / Arrays.sort works from the inside? I suppose not, otherwise they would not have asked such questions. But that's okay. Enjoy . - falstaf

1 answer 1

It is not clear how an anonymous class works?

It works like you code it. in the example above, he does the following:

 return a < b ? 1 : a == b ? 0 : -1; // if (a<b) return 1; if (a==b) return 0 else return -1; 

How are items from list taken and passed as parameters to the compare () method?

The sort method of the Collections class implements one of the sorting algorithms that your “custom” comparator uses for comparing elements.