java arraylist确保容量不起作用 [英] java arraylist ensureCapacity not working

查看:30
本文介绍了java arraylist确保容量不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要么我做错了,要么我不明白这个方法是如何工作的.

Either I'm doing this wrong or i'm not understanding how this method works.

ArrayList<String> a = new ArrayList<String>();
a.ensureCapacity(200);
a.add(190,"test");
System.out.println(a.get(190).toString());

我本以为 ensureCapacity 会让我插入一个索引高达该值的记录.有没有其他方法可以做到这一点?

I would have thought that ensureCapacity would let me insert a record with an index up to that value. Is there a different way to do this?

我在第三行收到 IndexOutOfBounds 错误.

I get an IndexOutOfBounds error on the third line.

推荐答案

不,ensureCapacity 不会改变 ArrayList逻辑大小> - 它改变了容量,这是列表在下一次需要复制值之前可以达到的大小.

No, ensureCapacity doesn't change the logical size of an ArrayList - it changes the capacity, which is the size the list can reach before it next needs to copy values.

您需要非常清楚逻辑大小之间的区别(即[0, size) 范围内的所有值都是可访问的,添加新元素会将其添加到索引size) 和容量,它实际上更像是一个实现细节 - 它是用于存储的后备数组的大小.

You need to be very aware of the difference between a logical size (i.e. all the values in the range [0, size) are accessible, and adding a new element will add it at index size) and the capacity which is more of an implementation detail really - it's the size of the backing array used for storage.

调用 ensureCapacity 应该只会在性能方面产生任何差异(通过避免过度复制) - 如果您明白我的意思,它不会影响列表中内容的逻辑模型.

Calling ensureCapacity should only ever make any difference in terms of performance (by avoiding excessive copying) - it doesn't affect the logical model of what's in the list, if you see what I mean.

听起来你想要一种 ensureSize() 方法,它可能看起来像这样:

It sounds like you want a sort of ensureSize() method, which might look something like this:

public static void ensureSize(ArrayList<?> list, int size) {
    // Prevent excessive copying while we're adding
    list.ensureCapacity(size);
    while (list.size() < size) {
        list.add(null);
    }
}

这篇关于java arraylist确保容量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆