gpt4 book ai didi

java - ArrayList 未设置最小容量

转载 作者:行者123 更新时间:2023-12-01 16:38:34 27 4
gpt4 key购买 nike

private static ArrayList<String> places(ArrayList<Road> roads) {
ArrayList<String> places = new ArrayList<String>(10); // tried setting minimum capacity
places.ensureCapacity(10); // tried setting minimum capacity

for (int i = 0; i < roads.size(); i++) {
String from = roads.get(i).getFrom();
String to = roads.get(i).getTo();

for (int j = 0; j < places.size(); j++) { // this is where things go wrong, it doesn't iterate because the "j < places.size()" condition isn't met
if ((places.get(i).equals(from))==false) {
places.add(from);
}
if ((places.get(i).equals(to))==false) {
places.add(to);
}
}
}

return places;
}

不知道为什么,但地方数组列表没有设置初始容量,这导致我稍后必须迭代地方时(处理 j 变量的 for 循环)。

最佳答案

最小容量与尺寸不同。设置容量只是对列表的一个提示,它应该至少有这么多存储空间以避免不必要的数组副本,但不会影响大小,因此即使您有 n 个元素的容量,size() 可以更少,并且调用 get(n-1) 可能会导致 IndexOutOfBoundsException

要创建一个大小为 n 且填充 null 的列表,请尝试

List<String> myList = new ArrayList<String>(n);
for (int i = 0; i < n; ++i) { myList.add(null); }

关于java - ArrayList<String> 未设置最小容量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6686434/

27 4 0