ArrayList 的起始大小
我想使用 ArrayList (或其他一些集合),就像使用标准数组一样。
具体来说,我希望它以初始大小(例如 SIZE)开始,并且能够立即显式设置元素,
例如
array[4] = "stuff";
可以编写
array.set(4, "stuff");
但是,以下代码会抛出 IndexOutOfBoundsException:
ArrayList<Object> array = new ArrayList<Object>(SIZE);
array.set(4, "stuff"); //wah wahhh
我知道有几种方法这样做,但我想知道是否有人们喜欢的一个,或者也许是一个更好的集合可以使用。目前,我正在使用如下代码:
ArrayList<Object> array = new ArrayList<Object>(SIZE);
for(int i = 0; i < SIZE; i++) {
array.add(null);
}
array.set(4, "stuff"); //hooray...
我什至问的唯一原因是因为我在一个可能会运行很多次(数万次)的循环中执行此操作。鉴于 ArrayList 调整大小行为是“未指定”的,我宁愿它不要浪费任何时间调整自身大小,也不要浪费内存在支持它的数组中额外的、未使用的点上。不过,这可能是一个有争议的问题,因为我将通过调用 array.set() 来完全填充数组(几乎总是数组中的每个单元格),并且永远不会超过容量?
我宁愿只使用普通数组,但我的规范要求我使用集合。
I want to use an ArrayList (or some other collection) like how I would use a standard array.
Specifically, I want it to start with an intial size (say, SIZE), and be able to set elements explicitly right off the bat,
e.g.
array[4] = "stuff";
could be written
array.set(4, "stuff");
However, the following code throws an IndexOutOfBoundsException:
ArrayList<Object> array = new ArrayList<Object>(SIZE);
array.set(4, "stuff"); //wah wahhh
I know there are a couple of ways to do this, but I was wondering if there was one that people like, or perhaps a better collection to use. Currently, I'm using code like the following:
ArrayList<Object> array = new ArrayList<Object>(SIZE);
for(int i = 0; i < SIZE; i++) {
array.add(null);
}
array.set(4, "stuff"); //hooray...
The only reason I even ask is because I am doing this in a loop that could potentially run a bunch of times (tens of thousands). Given that the ArrayList resizing behavior is "not specified," I'd rather it not waste any time resizing itself, or memory on extra, unused spots in the Array that backs it. This may be a moot point, though, since I will be filling the array (almost always every cell in the array) entirely with calls to array.set(), and will never exceed the capacity?
I'd rather just use a normal array, but my specs are requiring me to use a Collection.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
初始容量是指数组有多大。这并不意味着那里有元素。所以尺寸!=容量。
事实上,您可以使用数组,然后使用
Arrays.asList(array)
来获取集合。The initial capacity means how big the array is. It does not mean there are elements there. So size != capacity.
In fact, you can use an array, and then use
Arrays.asList(array)
to get a collection.我推荐一个HashMap
I recomend a HashMap
考虑到你的主要观点是记忆。然后,您可以手动执行 Java 数组列表的操作,但它不允许您根据需要调整大小。因此,您可以执行以下操作:
或者您可以实现一个列表(而不是向量)结构。我认为 Java 已经有了一个。
Considering that your main point is memory. Then you could manually do what the Java arraylist do, but it doesn't allow you to resize as much you want. So you can do the following:
Or you can implement a List (not vector) struct. I think Java already has one.
是的,哈希图将是一个很棒的想法。
换句话说,您可以根据您的目的启动具有大容量的阵列。
Yes, hashmap would be a great ideia.
Other way, you could just start the array with a big capacity for you purpose.