Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do ArrayLists that contain different types of objects use different amounts of memory?

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!

like image 935
qwertyuiop5040 Avatar asked Aug 09 '13 03:08

qwertyuiop5040


People also ask

Can ArrayList hold multiple object types?

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.

Can ArrayLists store different data types?

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).

How are ArrayLists stored in memory?

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.

Does ArrayList have contiguous memory?

ArrayLists use contiguous memory. All elements in the ArrayList are located next to each other in the same memory space.


1 Answers

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.

like image 90
Hovercraft Full Of Eels Avatar answered Sep 20 '22 15:09

Hovercraft Full Of Eels