Collections.reverse sorts the list collection in descending order

public class Test { public static void main(String[] args) { long[] data = {4, 3, 1, 8, 6, 9, 2}; List list = new ArrayList<>(); for (long key : data) { list.add(key); } System.out.println(list); //先升序 // Collections.sort(list); // System.out.println(list); //再反转 Collections.reverse(list); System.out.println(list); }

}

I accidentally searched the Collections.reverse method today, and found that some people misunderstood it quite deeply. The following is written by a blogger with millions of visits. Reverse can sort the specified list in descending order, but the output results are not in descending order. write picture description here

Indeed, using Collections.reverse in combination with certain methods can sort the list collection in descending order, but it is wrong to directly use Collections.reverse(list) to descend in this way. reverse means reverse, not descending. It just reverses the original order of the list collection. Reversal does not mean descending order. So if you want to achieve descending order, you can first ascend the collection, and then reverse, so that the descending order. for example:

import java.util. *;

public class Test { private static Map<Integer, String> map = new HashMap<Integer, String>();

public static void main(String[] args) { long[] data = {1506326821000l, 1506327060000l, 1506326880000l, 1506327000000l, 1506326940000l, 1506326760000l, 1506326700000l}; List list = new ArrayList<>(); for (long key : data) { list.add(key); } System.out.println(list); //先升序 Collections.sort(list); System.out.println(list); //再反转 Collections.reverse(list); System.out.println(list); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 输出:

[1506326821000, 1506327060000, 1506326880000, 1506327000000, 1506326940000, 1506326760000, 1506326700000] [1506326700000, 1506326760000, 1506326821000, 1506326880000, 1506326940000, 1506327000000, 1506327060000] [1506327060000, 1506327000000, 1506326940000, 1506326880000, 1506326821000, 1506326760000, 150

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325923956&siteId=291194637