如何在Java中获取ArrayList的容量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2497063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:27:25  来源:igfitidea点击:

How to get the capacity of the ArrayList in Java?

javacollections

提问by JavaUser

Its known that Java ArrayList is implemented using arrays and initializes with capacity of 10 and increases its size by 50% . How to get the current ArrayList capacity not the Size of the ArrayList.

众所周知,Java ArrayList 是使用数组实现的,初始化时容量为 10,大小增加 50%。如何获取当前 ArrayList 容量而不是 ArrayList 的大小。

Thx

谢谢

采纳答案by Mark B

I don't think this is possible. What is your use case? I believe C# ArrayLists have a .capacityproperty, but the Java ArrayList class doesn't expose this information.

我不认为这是可能的。你的用例是什么?我相信 C# ArrayLists 有一个.capacity属性,但 Java ArrayList 类不公开此信息。

You have the constructor that takes an initial capacity argument, and you have the ensureCapacity()method which you could use to reduce the amount of incremental reallocation.

您拥有接受初始容量参数的构造函数,并且拥有ensureCapacity()可用于减少增量重新分配量的方法。

You also have the trimToSize()method you can use if you are really worried about memory usage.

trimToSize()如果您真的担心内存使用,您也可以使用该方法。

回答by instcode

Don't remember if it has but you could do it yourself by looking at the source code of ArrayList. Java developers should take advantage of the source code bundled with the SDK.

不记得是否有,但您可以通过查看 ArrayList 的源代码自己完成。Java 开发人员应该利用与 SDK 捆绑在一起的源代码。

回答by chama

I just checked out the sun documentation on the ArrayListclass, and the only method I saw that related to the capacity was ensureCapacity(int minCapacity), which is not exactly what you want. Good luck!

我刚刚查看了有关ArrayList类的 sun 文档,我看到的与容量相关的唯一方法是 ensureCapacity(int minCapacity),这不是您想要的。祝你好运!

回答by Itay Maman

Looking at ArrayList's specI see no method that provides this information.

查看ArrayList 的规范,我看不到提供此信息的方法。

That said, the ensureCapacitymethod does seem like a step in the right direction (caution: it is does not guarantee a correct answer): When called it ensures that the capacity is at least the specified argument. So, if the ArrayListimplementation uses this method to ensure capacity (as opposed to calling some private method/manipulating the relevant fields directly) you can obtain the current capacity by overriding this method. You also need to override trimToSize()in a similar manner.

也就是说,ensureCapacity方法似乎是朝着正确方向迈出的一步(注意:它不保证正确答案):调用时,它确保容量至少是指定的参数。因此,如果ArrayList实现使用此方法来确保容量(而不是调用某些私有方法/直接操作相关字段),则可以通过覆盖此方法来获取当前容量。您还需要以trimToSize()类似的方式覆盖。

Of course, this solution is not very portable as a different implementation of ArrayList(on a JVM from another vendor) may do things differently.

当然,这个解决方案不是很可移植,因为ArrayList(在另一个供应商的 JVM 上)的不同实现可能会做不同的事情。

Here's how the code should look like

下面是代码的样子

public class CapacityTrackingArrayList<T> extends ArrayList<T> {

   // declare a constructor for each ArrayList constructor ...


   // Now, capacity tracking stuff:
   private int currentCapacity = 10;

   public int getCapacity() { return currentCapacity; }

   public void ensureCapacity(int arg) {
     currentCapacity = arg;
     super.ensureCapacity(arg);
   }

   public void trimToSize() { currentCapacity = size(); super.trimToSize(); }

}

回答by pgras

You can get it by reflection:

你可以通过反射得到它:

public abstract class ArrayListHelper {

    static final Field field;
    static {
        try {
            field = ArrayList.class.getDeclaredField("elementData");
            field.setAccessible(true);
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    @SuppressWarnings("unchecked")
    public static <E> int getArrayListCapacity(ArrayList<E> arrayList) {
        try {
            final E[] elementData = (E[]) field.get(arrayList);
            return elementData.length;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}

回答by user2632932

You can use Vector instead of ArrayList. Vector supports capacity() method.

您可以使用 Vector 而不是 ArrayList。Vector 支持 capacity() 方法。

回答by Nishant Srivastava

Default capacity of ArrayListis 10.once the max size is reached,new capacity will be:

默认容量ArrayList为 10。一旦达到最大大小,新容量将是:

new capacity=(currentcapacity*3/2)+1.

新容量=(当前容量*3/2)+1。

回答by K_holla

The whole point of using ArrayList is to dynamically add new element, So there is no specific method to get the capacity of the ArrayList.

使用 ArrayList 的全部意义在于动态添加新元素,因此没有具体的方法来获取 ArrayList 的容量。

Every time we add an element dynamically causes reallocation and since reallocation is costly in terms of time, preventing reallocation improves performance and hence you can manually increase the capacity of ArrayList by calling ensureCapacity() but again you can not find out the capacity of the ArrayList.

每次我们动态添加元素都会导致重新分配,并且由于重新分配在时间上是昂贵的,因此防止重新分配可以提高性能,因此您可以通过调用 ensureCapacity() 手动增加 ArrayList 的容量,但您再次无法找出 ArrayList 的容量.

回答by Shaun Dashjian

You can get the current capacity of an ArrayList in Java using reflection. Here is an example:

您可以使用反射在 Java 中获取 ArrayList 的当前容量。下面是一个例子:

package examples1;

import java.util.ArrayList;
import java.util.List;
import java.lang.reflect.Field;

public class Numbers {

    public static void main(String[] args) throws Exception {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        System.out.println(getCapacity(numbers));
    }

    static int getCapacity(List al) throws Exception {
        Field field = ArrayList.class.getDeclaredField("elementData");
        field.setAccessible(true);
        return ((Object[]) field.get(al)).length;
    }
}

This will output: 10

这将输出: 10

Notes:

笔记:

  1. getCapacity()method modified from the original at http://javaonlineguide.net/2015/08/find-capacity-of-an-arraylist-in-java-size-vs-capacity-in-java-list-example.html
  2. Note that the default capacity of 10 is granted after the first add to the list. If you try this before adding, you will get an output of 0
  3. To force a capacity without adding, pass it in the constructor like so:

    List<Integer> numbers = new ArrayList<>(20);
    
  1. getCapacity()http://javaonlineguide.net/2015/08/find-capacity-of-an-arraylist-in-java-size-vs-capacity-in-java-list-example.html的原始方法修改而来的方法
  2. 请注意,在第一次添加到列表后授予默认容量 10。如果你在添加之前尝试这个,你会得到一个输出0
  3. 要强制容量而不添加,请将其传递到构造函数中,如下所示:

    List<Integer> numbers = new ArrayList<>(20);