How to sort a List of objects by their date (java collections, List<Object>)

前端 未结 6 1402
迷失自我
迷失自我 2020-12-25 15:20
private List movieItems = null;
public List getMovieItems() {
    final int first = 0;
    if (movieItems == null) {
        getPagingInfo(         


        
6条回答
  •  太阳男子
    2020-12-25 15:26

    Do not access or modify the collection in the Comparator. The comparator should be used only to determine which object is comes before another. The two objects that are to be compared are supplied as arguments.

    Date itself is comparable, so, using generics:

    class MovieComparator implements Comparator {
        public int compare(Movie m1, Movie m2) {
           //possibly check for nulls to avoid NullPointerException
           return m1.getDate().compareTo(m2.getDate());
        }
    }
    

    And do not instantiate the comparator on each sort. Use:

    private static final MovieComparator comparator = new MovieComparator();
    

提交回复
热议问题