Java8 Collections.sort (sometimes) does not sort JPA returned lists

后端 未结 3 700
攒了一身酷
攒了一身酷 2020-11-28 12:24

Java8 keeps doing strange things in my JPA EclipseLink 2.5.2 environment. I had to delete the question https://stackoverflow.com/questions/26806183/java-8-sorting-behaviour

3条回答
  •  失恋的感觉
    2020-11-28 12:50

    The issue you are having is not with sort.

    TimSort is called via Arrays.sort which does the following:

    TimSort.sort(a, 0, a.length, c, null, 0, 0);
    

    So you can see the size of the array TimSort is getting is either 0 or 1.

    Arrays.sort is called from Collections.sort, which does the following.

    Object[] a = list.toArray();
    Arrays.sort(a, (Comparator)c);
    

    So the reason your collection is not getting sorted is that it is returning an empty array. So the collection that is being used is not conforming to the collections API by returning an empty array.

    You say you have a persistence layer. So it sounds like the problem is that the library you are using retrieves entities in a lazy way and does not populate its backing array unless it has to. Have a closer look at the collection you are trying to sort and see how it works. Your original unit test didn't show anything as it was not trying to sort the same collection that is used in production.

提交回复
热议问题