For example, if you were to have
int a=2; int b=3;
ArrayList<Integer>integers=new ArrayList<Integer>();
integers.add(a); integers.add(b);
and
String c="cow"; String d="deer";
ArrayList<String> strings= new ArrayList<String>();
strings.add(c); strings.add(d);
Would they take different amounts of memory? Any help/answer would be highly appreciated, thanks!
It is more common to create an ArrayList of definite type such as Integer, Double, etc. But there is also a method to create ArrayLists that are capable of holding Objects of multiple Types. We will discuss how we can use the Object class to create an ArrayList. Object class is the root of the class hierarchy.
ArrayList cannot hold primitive data types such as int, double, char, and long. With the introduction to wrapped class in java that was created to hold primitive data values. Objects of these types hold one value of their corresponding primitive type(int, double, short, byte).
The elements of an ArrayList are stored in a chunk of contiguous memory. When that memory becomes full, a larger chunk of contiguous memory has to be allocated (usually twice the size) and the existing elements are copied into this new chunk. We call this chunk the capacity of the ArrayList object.
ArrayLists use contiguous memory. All elements in the ArrayList are located next to each other in the same memory space.
The ArrayLists themselves are nothing more than a collection of references, and these take the same amount of memory (if the same size) no matter the type of objects they hold. However the items referred to by the ArrayList all take differing amounts of memory as you would expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With