我不是一个真正的专家,也无法弄清楚为什么会越界
public class ParticipantIndexComparator implements Comparator<Integer> {
final List<Participant> participants;
public ParticipantIndexComparator(ArrayList<Integer> numbersToSort) {
Log.d("MyLog","numbersToSort.size=" + numbersToSort.size());
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);
}
Log.d("MyLog","participants.size="+participants.size());
}
@Override
public int compare(Integer i1, Integer i2) {
Log.d("MyLog","in compare: participants.size=" + participants.size() + "i1=" + i1 + " i2=" + i2);
long l1 = participants.get(i1).kpTime.get(kpSelected);
long l2 = participants.get(i2).kpTime.get(kpSelected);
return Long.valueOf(l1).compareTo(Long.valueOf(l2));
}
}
好吧,我的第一个日志显示了我
participants.size=8.
第二个日志显示我
participants.size=8.
第三个日志显示了我
participants.size=8, i1=13 i2=14.
为什么???当我每一步检查尺寸时,为什么总是13和14,而总是8?我听不懂。我不是专家,我自己也无法弄清楚
这是stacktrace:
11-24 02:41:23.612: E/AndroidRuntime(4802): java.lang.IndexOutOfBoundsException: Invalid index 14, size is 8
11-24 02:41:23.612: E/AndroidRuntime(4802): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
11-24 02:41:23.612: E/AndroidRuntime(4802): at java.util.ArrayList.get(ArrayList.java:304)
11-24 02:41:23.612: E/AndroidRuntime(4802): at ru.maximhasanov.skitimer.FinalProtocolActivity$ParticipantIndexComparator.compare(FinalProtocolActivity.java:311)
11-24 02:41:23.612: E/AndroidRuntime(4802): at ru.maximhasanov.skitimer.FinalProtocolActivity$ParticipantIndexComparator.compare(FinalProtocolActivity.java:1)
11-24 02:41:23.612: E/AndroidRuntime(4802): at java.util.TimSort.countRunAndMakeAscending(TimSort.java:320)
11-24 02:41:23.612: E/AndroidRuntime(4802): at java.util.TimSort.sort(TimSort.java:185)
11-24 02:41:23.612: E/AndroidRuntime(4802): at java.util.TimSort.sort(TimSort.java:169)
11-24 02:41:23.612: E/AndroidRuntime(4802): at java.util.Arrays.sort(Arrays.java:2038)
11-24 02:41:23.612: E/AndroidRuntime(4802): at java.util.Collections.sort(Collections.java:1891)
11-24 02:41:23.612: E/AndroidRuntime(4802): at ru.maximhasanov.skitimer.FinalProtocolActivity.sortNumbers(FinalProtocolActivity.java:213)
最佳答案
好的,我要试一下。我想我对您的情况有所了解。
正如我在评论中说的那样,我认为numbersToSort
包含要根据特定competition.participant
排序的kpTime
子集的数字(基本上是索引)的列表。
如果这是正确的,那么得到OutOfBoundsException
的原因是因为numbersToSort
包含大于participants
大小的数字(它们是索引),因为participants
是更大的子集。清单。
我相信您应该做的是在ArrayList<Participant> participants
的 sortNumbers
方法中创建您的FinalProtocolActivity
,然后使用以下Collections.sort()
在其上调用Comparator
:
public class ParticipantIndexComparator implements Comparator<Participant>
{
public int compare(Participant p1, Participant p2)
{
Long time1 = p1.kpTime.get(kpSelected);
Long time2 = p2.kpTime.get(kpSelected);
return Long.valueOf(time1).compareTo(time2);
}
}