【问题标题】:Java - ComparatorJava - 比较器
【发布时间】:2013-12-08 08:25:43
【问题描述】:

我有关于 Comparator 的问题 - 我需要对我的 ArrayList<Integer> numbersToSort 进行排序,它保留数字 - 链接到 competition.participant.get(numbers.get(index)) - 所以我有一个主要对象 - 有一个参与者列表对象的竞赛。所以,我的ArrayList<Integer> numbersToSort 保留了我应该使用哪些数量的competition.participants。我想出如何对我的ArrayList<Integer> numbersToSort(我稍后将提供给我的 ListView 适配器)进行排序的唯一方法是创建另一个“并行”List<Participants>,我将从主要对象、比赛中复制参与者并将他们的号码存储在ArrayList<Integer> numbersToSort 所以我以后可以从排序的List<Participant> participants 中组装一个新的ArrayList<Integer> sortedNumbers。你还在吗?:)

    public class ParticipantIndexComparator implements Comparator<Integer> {
        final List<Participant> participants;       
        public ParticipantIndexComparator(ArrayList<Integer> numbersToSort) {
            participants=new ArrayList<Participant>();
            for (int i=0;i<numbersToSort.size();i++)
            { participants.add(i,competition.participant.get(numbersToSort.get(i))); participants.get(i).comparator=numbersToSort.get(i);}

        }

        @Override
        public int compare(Integer i1, Integer i2) {
            long l1 = participants.get(i1).kpTime.get(kpSelected); 
//time from selected checkpoint
            long l2 = participants.get(i2).kpTime.get(kpSelected);
            return (long) compare(l1, l2);
        }
    }

好吧,问题是最后一次return (long) compare(l1, l2); - 是的,我知道这不对,但这是第 30 次尝试 :) 请纠正错误

【问题讨论】:

  • 为什么要转换为长?你试过去掉演员表吗?这看起来像一个递归调用。尝试返回 (int)(l1-l2)
  • 更正。需要比较传递给 compare() 方法的 int 值。返回 i1 - i2。
  • 因为我需要准确地比较这些 2 个 longs

标签: java android arraylist comparator


【解决方案1】:
@Override
public int compare(Integer i1, Integer i2) {
    long l1 = participants.get(i1).kpTime.get(kpSelected); 
    long l2 = participants.get(i2).kpTime.get(kpSelected);
    return Long.compare(l1, l2);
}

【讨论】:

【解决方案2】:

试试这个:

        public int compare(Integer lhs,
                        Integer rhs) {
                    return lhs - rhs;
                }
            });

【讨论】:

    猜你喜欢
    • 2013-09-04
    • 1970-01-01
    • 2018-11-27
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    相关资源
    最近更新 更多