Java中如何获取ArrayList的容量?

发布于 2024-08-26 12:28:24 字数 102 浏览 3 评论 0原文

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

谢谢

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.

Thx

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

少钕鈤記 2024-09-02 12:28:24

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

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

如果您确实担心内存使用情况,还可以使用 trimToSize() 方法。

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

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.

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

感情废物 2024-09-02 12:28:24

你可以通过反射得到它:

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);
        }

    }
}

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);
        }

    }
}
青朷 2024-09-02 12:28:24

在 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;
    }
}

这将输出: 10

注释:

  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. 要强制容量而不添加,请将其传递到构造函数中,如下所示:

    列表<整数>数字 = new ArrayList<>(20);
    

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

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

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);
    
秋日私语 2024-09-02 12:28:24

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

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

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

代码应该是这样的

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(); }

}

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

That said, the ensureCapacity method 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 ArrayList implementation 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.

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

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(); }

}
眼角的笑意。 2024-09-02 12:28:24

您可以使用 Vector 代替 ArrayList。 Vector支持capacity()方法。

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

以酷 2024-09-02 12:28:24

使用ArrayList的全部目的是动态添加新元素,因此没有特定的方法来获取ArrayList的容量。

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

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.

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.

岁月打碎记忆 2024-09-02 12:28:24

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

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

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

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

对你的占有欲 2024-09-02 12:28:24

我认为没有直接的方法来检查 ArrayList 容量。但是,有一种方法可以检查数组列表的大小。

sopln(arraylist.size());

你可以在采访中这样说。我们无法得知 ArrayList 的容量,但我们可以检查其大小。然后根据大小,我们就可以自己计算出Capacity了。 Arraylist 的初始容量 = 10。当它已满时,将形成新的 List,其容量为 CurrentCapacity * (3/2) +1 。所以,在这个方法中,你可以计算ArrayList的容量。

I dont think there is a direct method to check ArrayList Capacity. But, there is a method to Check the Size of the array list.

s.o.p.ln(arraylist.size());

You can say this in interview. We cannot tell the ArrayList Capacity, but we can check the Size. Then, according to the size, we can calculate the Capacity by our own. Initial Capacity of Arraylist = 10. When it is full, new List is formed with a Capacity of CurrentCapacity * (3/2) +1 . So, in this method, you can calculate the capacity of ArrayList.

oО清风挽发oО 2024-09-02 12:28:24

java中ArrayList的默认容量是2。我无法找到我不久前读过的模糊文档。但初始化时大小将为零。
一旦我们添加第三个元素,它将在另一个内存位置创建一个容量双倍的数组。引用将相应地移动,并且先前的数组将被垃圾收集

The default capacity is 2 for an Array List in java. I am not able to find the vague documentation I read a while ago. But the size will be zero upon initialization.
Once we add the third element it will creates an array of double the capacity in another memory location. The reference will be shifted accordingly and the previous array will be garbage collected

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文