Get capacity arraylist java

Capacity of ArrayList [duplicate]

Unfortunately not part of the API, but a bit annoying how many people in the answers are either not answering the question or answering the wrong question.

You can’t without a reflection hack, ArrayList doesn’t support capacity ordinarily. If you need this data, just use a Vector instead

8 Answers 8

I’m curious, what do you need it for? You should know that the capacity is not (as it may sound) an upper limit of how much you can put into the ArrayList. It’s a value representing how much data you can put into the list, without forcing it to reallocate it internal array. Basically, the notion of capacity is only there in order for you to tweak the performance slightly.

Anyway, perhaps you already know that, so here comes the actual answer.

The interface provided by API for ArrayList simply doesn’t support such use case. There are many reasons for this. One reason is that you shouldn’t care about this. The ArrayList is to be thought of as an unbounded array which abstracts away from details such as capacity.

The closest you can get to controlling the capacity is through the constructor ArrayList(int initialCapacity) , and the two methods trimToSize() and ensureCapacity(int minCapacity) .

For fun however, I managed to solve it through an ugly reflection-hack (don’t use this):

import java.lang.reflect.Field; import java.util.ArrayList; public class Test < public static void main(String[] args) throws Exception < ArrayListlist = new ArrayList(3); for (int i = 0; i < 17; i++) < list.add(i); System.out.format("Size: %2d, Capacity: %2d%n", list.size(), getCapacity(list)); >> static int getCapacity(ArrayList l) throws Exception < Field dataField = ArrayList.class.getDeclaredField("elementData"); dataField.setAccessible(true); return ((Object[]) dataField.get(l)).length; >> 
Size: 1, Capacity: 3 Size: 2, Capacity: 3 Size: 3, Capacity: 3 Size: 4, Capacity: 5 Size: 5, Capacity: 5 Size: 6, Capacity: 8 Size: 7, Capacity: 8 Size: 8, Capacity: 8 Size: 9, Capacity: 13 Size: 10, Capacity: 13 Size: 11, Capacity: 13 Size: 12, Capacity: 13 Size: 13, Capacity: 13 Size: 14, Capacity: 20 Size: 15, Capacity: 20 Size: 16, Capacity: 20 Size: 17, Capacity: 20 

Источник

Читайте также:  Css изменить цвет элемента

How to get the capacity of the arraylist in java?

ArrayList in Java is an implementation of the List interface that uses an array to store the elements. The capacity of an ArrayList is the number of elements that it can hold without having to resize the underlying array. It is important to keep track of the capacity of an ArrayList in order to optimize its performance and avoid unnecessary resizing operations. In this article, we will discuss two ways to get the capacity of an ArrayList in Java.

Method 1: Using the size() and elementData.length Properties

To get the capacity of an ArrayList in Java using the size() and elementData.length properties, you can follow these steps:

ArrayListString> myArrayList = new ArrayListString>();
myArrayList.add("element 1"); myArrayList.add("element 2"); myArrayList.add("element 3");
int size = myArrayList.size();
int capacity = ((Object[]) myArrayList.getClass() .getDeclaredField("elementData") .get(myArrayList)).length;
System.out.println("Size of ArrayList: " + size); System.out.println("Capacity of ArrayList: " + capacity);

Here is the complete code:

import java.util.ArrayList; public class ArrayListCapacityExample  public static void main(String[] args) throws Exception  // Create an instance of the ArrayList class ArrayListString> myArrayList = new ArrayListString>(); // Add elements to the ArrayList myArrayList.add("element 1"); myArrayList.add("element 2"); myArrayList.add("element 3"); // Get the size of the ArrayList int size = myArrayList.size(); // Get the capacity of the ArrayList int capacity = ((Object[]) myArrayList.getClass() .getDeclaredField("elementData") .get(myArrayList)).length; // Print the size and capacity of the ArrayList System.out.println("Size of ArrayList: " + size); System.out.println("Capacity of ArrayList: " + capacity); > >
Size of ArrayList: 3 Capacity of ArrayList: 10

In this example, we created an instance of the ArrayList class and added elements to it. We then used the size() method to get the size of the ArrayList and the elementData.length property to get the capacity of the ArrayList. Finally, we printed the size and capacity of the ArrayList.

Method 2: Using Reflection

To get the capacity of an ArrayList in Java using Reflection, you can follow these steps:

  1. Get the ArrayList class object using the getClass() method.
  2. Get the elementData field of the ArrayList using the getDeclaredField() method.
  3. Set the accessible property of the field to true using the setAccessible() method.
  4. Get the capacity field of the elementData array using the get() method.
import java.lang.reflect.Field; import java.util.ArrayList; public class ArrayListCapacityExample  public static void main(String[] args) throws Exception  ArrayListString> list = new ArrayList>(10); int capacity = getArrayListCapacity(list); System.out.println("Capacity of ArrayList: " + capacity); > private static int getArrayListCapacity(ArrayList?> list) throws Exception  Field field = ArrayList.class.getDeclaredField("elementData"); field.setAccessible(true); Object[] elementData = (Object[]) field.get(list); return elementData.length; > >

In this example, we create an ArrayList with an initial capacity of 10. We then call the getArrayListCapacity() method to get the capacity of the ArrayList using Reflection. The getArrayListCapacity() method takes an ArrayList as a parameter and returns its capacity as an integer.

We first get the elementData field of the ArrayList using the getDeclaredField() method. We then set the accessible property of the field to true using the setAccessible() method to allow us to access the private field. We then get the value of the elementData field using the get() method and cast it to an array of objects. Finally, we return the length of the array, which is the capacity of the ArrayList.

Источник

Get capacity arraylist java

Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.) The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation. Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost. An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation. Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

List list = Collections.synchronizedList(new ArrayList(. ));

The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework.

Field Summary

Fields declared in class java.util.AbstractList

Constructor Summary

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.

Method Summary

Inserts all of the elements in the specified collection into this list, starting at the specified position.

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator.

Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list.

Removes from this list all of the elements whose index is between fromIndex , inclusive, and toIndex , exclusive.

Returns a view of the portion of this list between the specified fromIndex , inclusive, and toIndex , exclusive.

Returns an array containing all of the elements in this list in proper sequence (from first to last element).

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.

Источник

Оцените статью