首頁  >  問答  >  主體

java Comparator为什么没完成排序?

            int top = Integer.parseInt(map.get("top"));
            List<NovelNews> novelNewsList = NovelMongo.GetAllNovel();
            Collections.sort(novelNewsList, new Comparator() {
                public int compare(Object obj0, Object obj1) {
                    NovelNews novel0 = (NovelNews) obj0;
                    NovelNews novel1 = (NovelNews) obj1;
                    return Long.toString(novel1.getHeat()).compareTo(Long.toString(novel0.getHeat()));
                }
            });
                        
            for(int i = 0; i <= top - 1; i++){
                System.out.println(novelNewsList.get(i).getHeat());                
            }
高洛峰高洛峰2765 天前341

全部回覆(1)我來回復

  • 阿神

    阿神2017-04-18 10:26:13

    ...
    return Long.toString(novel1.getHeat()).compareTo(Long.toString(novel0.getHeat()));

    String.compareTo(String arg);是依照字典排序的規則,而不是比較值的大小,範例如下:
    23
    2231
    223
    123
    想要依照Long型值的大小排序:

    ...
    return novel0.getHeat().compareTo(novel1.getHeat());

    回覆
    0
  • 取消回覆