java:自定义排序

   /**
     * 升序  如果o1小于o2,返回一个负数;如果o1大于o2,返回一个正数;如果他们相等,则返回0;
     */
    Comparator<Object> comparator_up = new Comparator<Object>(){
        @Override
        public int compare(Object s1, Object s2) {
            int o1 = 0;
            int o2 = 0;
            if(s1 instanceof Pop && s2 instanceof Pop){
                try{
                    o1 = Integer.valueOf(((Pop) s1).getStation());
                    o2 = Integer.valueOf(((Pop) s2).getStation());
                }catch (Exception e){
                    return 0;
                }
            }
            if(o1 < o2) return -1;
            if(o1 > o2) return 1;
            return 0;
        }
    };
 /**
     * 降序  如果o1小于o2,返回一个正数;如果o1大于o2,返回一个负数;如果他们相等,则返回0;
     */
  Comparator<Object> comparator_down = new Comparator<Object>(){
        @Override
        public int compare(Object s1, Object s2) {
            int o1 = 0;
            int o2 = 0;
            if(s1 instanceof Pop && s2 instanceof Pop){
                try{
                    o1 = Integer.valueOf(((Pop) s1).getStation());
                    o2 = Integer.valueOf(((Pop) s2).getStation());
                }catch (Exception e){
                    return 0;
                }
            }
            if(o1 < o2) return 1;//
            if(o1 > o2) return -1;
            return 0;
        }
    };

if(order == 1){//升序
Collections.sort(list_pop,comparator_up);
}else if(order == 2){//降序
Collections.sort(list_pop,comparator_down);
}

猜你喜欢

转载自blog.csdn.net/xdy1120/article/details/82464336
今日推荐