we know the .size() method that returns the number of elements in an array list but is there a way to access the capacity of it (of a known class type not a general method ), not a reserved method, but if there is anything in your minds
Asked
Active
Viewed 27 times
0
-
3You can get it with `capacity()`, but you don't need to care about it as it's an implementation detail. Based on your other question it seems like you think an `ArrayList` should have "empty indexes", it shouldn't. It should have a certain amount of elements, which you get with `size()`. You can add and remove elements from the list, and it will resize itself accordingly. – Kayaman Dec 17 '21 at 12:05
-
Here is a good read about this: https://www.baeldung.com/java-list-capacity-array-size – xMilos Dec 17 '21 at 12:05
-
@Kayaman i realize how the arraylist reallocating work, but a strict professor wanted me to declare an arraylist with given capacity and he wants me to allow the user keep adding elements to the arraylist until the capacity is reached, i told him if he wanted something like that i would go for normal array which has a fixed limit once you create it, but he wants me to figure this out lol.. – RoronoaNewJavaBoy Dec 17 '21 at 12:16
-
Fine. Declare a `List` with a given capacity. When you try to add, check if the size is less than the capacity. If so, add. If not, send an error message. – Gilbert Le Blanc Dec 17 '21 at 14:30