java - 如何按日期对对象列表进行排序(java 集合,List<Object>)

标签 java sorting collections

private List<Movie> movieItems = null;
public List<Movie> getMovieItems() {
    final int first = 0;
    if (movieItems == null) {
        getPagingInfo();
        movieItems = jpaController.findRange(new int[]{pagingInfo.getFirstItem(), pagingInfo.getFirstItem() + pagingInfo.getBatchSize()});
        Collections.sort(movieItems, new Comparator(){
           public int compare (Object o1, Object o2){
               Date d1 = movieItems.get(((Movie)o1).getMovieId()).getDate();
               Date d2 = movieItems.get(((Movie)o2).getMovieId()).getDate();
               if(d1.before(d2)){
                   movieItems.set(1, (Movie)o1);
                   movieItems.set(2, (Movie)o2);
               }
               return first;
           }
       });
    }
    return movieItems;
}

jpaController 正在带回 4 部电影并为我提供以下内容

java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 4 at java.util.Vector.get(Vector.java:694) at entitybeans.jsf.PeliculaController$1.compare(PeliculaController.java:260) at java.util.Arrays.mergeSort(Arrays.java:1270) at java.util.Arrays.sort(Arrays.java:1210) at java.util.Collections.sort(Collections.java:159) at entitybeans.jsf.PeliculaController.getPeliculaItems(PeliculaController.java:257) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at javax.el.BeanELResolver.getValue(BeanELResolver.java:302) at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:175) at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72) at com.sun.el.parser.AstValue.getValue(AstValue.java:116) at com.sun.el.parser.AstValue.getValue(AstValue.java:163)....

最佳答案

在您的compare 方法中,o1o2 已经是movieItems 列表中的元素。所以,你应该这样做:

Collections.sort(movieItems, new Comparator<Movie>() {
    public int compare(Movie m1, Movie m2) {
        return m1.getDate().compareTo(m2.getDate());
    }
});

关于java - 如何按日期对对象列表进行排序(java 集合,List<Object>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5207029/

相关文章:

c - 修改合并排序以存储原始索引

java - 有没有更好的方法来通过对对象数组执行碰撞检测?

java - 有没有办法通过java来控制鼠标?

java - xml 节点上的 getTextContent 返回空指针异常

javascript - 排序 HTML 表格无法正常工作

java - 当依赖属性更改时如何在实体上设置 ModifiedDate

java - QuickBooks 在线修改发票

json - 如何在 go lang 中对 map[string]interface{} 类型进行多重排序?

ios - 标题 Collection View 中的分组数据

java - PHP 中有相当于 Java Set 的东西吗?