Obtain capacity of an ArrayList

2

In an exercise I am asked to obtain the size and capacity of a previously filled Vector and ArrayList.

In the case of the vector there are not many problems to do it, because it has a method.

Vector<Object> planetas = new Vector<>();

    planetas.add("Jupiter");
    planetas.add("Marte");
    planetas.add("Mercurio");
    planetas.add("Neptuno");
    planetas.add("Pluton");
    planetas.add("Saturno");
    planetas.add("Tierra");
    planetas.add("Urano");
    planetas.add("Venus");

System.out.println(planetas.size());
System.out.println(planetas.capacity());

But my problem is with the ArrayList, that if I have the .size () method but there is nothing similar to the .capacity () of the Vector.

Can you tell me if there is a method or some way to obtain the capacity?

    
asked by Pablo Pérez-Aradros 15.09.2016 в 10:16
source

1 answer

3

From Javadoc .

  

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.

It follows that there are two possible answers:

  • "It is not known exactly, but at least it is" + miArrayList.size (). You can also add "and at the most is the maximum array length supported by the JVM" (although I find it a bit pedantic)

  • Use trimToSize() and then say that the capacity is miArrayList.size() .

I would vote for the first answer, it would be a question to see if the difference between specification and implementation is distinguished.

    
answered by 15.09.2016 / 10:26
source