gpt4 book ai didi

java - 非顺序索引集合

转载 作者:行者123 更新时间:2023-11-30 08:34:57 26 4
gpt4 key购买 nike

我有一个对象集合,我需要一个迭代器,它可以按顺序(向前和向后)遍历对象,但也可以在给定该对象的索引(代表类(class)编号)时转到任何对象作业)。

但是,每个对象的索引都需要按顺序专门预定义,并且不能保证我的对象列表会有顺序索引(例如,我可以有索引 0、1、6、9)。

我目前有一个 ArrayList(),我正在用我希望可能作为初始容量的 largestIndex 实例化它,但是每当我尝试在我的 ArrayList 上使用 add(index, Object) 方法时,我总是收到 ArrayIndexOutOfBounds 异常

我的代码是这样的:

    int largestIndex = unindexedAssignments.get(unindexedAssignments.size() - 1).getAssignmentID();
//index of 0 is ignored so add +1 to make sure we have enough space
assignments = new ArrayList<>(largestIndex + 1);

System.out.println("LargestIndex: " + (largestIndex + 1));

//populate assignments List
for(Assignment assignment : unindexedAssignments) {
//add the assignment to the list such that the index == the lesson number
System.out.println("adding assignment with index of " + assignment.getAssignmentID());
assignments.add(assignment.getAssignmentID(), assignment);
}

然后控制台吐出这样的东西(windows cmdpromt 不支持复制/粘贴>_<):

largestIndex: 3
adding assignment with index of 1
java.lang.IndexOutOfBoundsException: Index 1, Size: 0
at java.util.ArrayList.rangeCheckForAdd(Unkown Source)
at java.util.ArrayList.add(Unknown Source)
(the rest of the stack trace pointing to the section of code I gave above ...)

我不明白为什么当我创建应该是大小为 4 的 ArrayList 时 Size == 0?

一个相关的问题:当有更好的默认 Java 集合可用于这种情况时,我是否滥用了 ArrayList(它是 ListIterator)?期望的最终结果是我的对象有一个 Iterator 对象,它能够来回遍历并转到特定位置(现在我只会在给定索引处创建一个新的 ListIterator,如果它存在的话)

最佳答案

List 不支持稀疏索引。如果要添加到列表末尾之后的索引,则还必须创建所有中间索引。

使用 SortedMap。 map 非常适合具有非连续索引的情况。您可以按类(class)编号查找任何作业,并且可以按顺序遍历所有键值对。

SortedMap<Integer, Assignment> assignments = new TreeMap<>();

for (Assignment assignment: unindexedAssignments) {
assignments.put(assignment.getAssignmentID(), assignment);
}

您还可以使用 Java 8 流语法作为显式循环的替代方法。

Map<Integer, Assignment> assignments = unindexedAssignments.stream()
.collect(Collectors.toMap(
a -> a.getAssignmentID(), // keys
a -> a, // values
(a, b) -> throw new IllegalStateException("duplicate lesson number"),
// what to do if two items have the same key
TreeMap::new // map class constructor
));

关于java - 非顺序索引集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38545373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com