The ArrayList
class can only contain references to objects but what happens when you store a value type such as integers?
string str = "Hello";
int i = 50;
ArrayList arraylist = new ArrayList();
arraylist.Add(str); // Makes perfectly sense:
// Reference to string-object (instance) "Hello" is added to
// index number 0
arraylist.Add(i); // What happens here? How can a reference point to a value
// type? Is the value type automatically converted to an
// object and thereafter added to the ArrayList?
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).
We can use the Object class to declare our ArrayList using the syntax mentioned below. ArrayList<Object> list = new ArrayList<Object>(); The above list can hold values of any type. The code given below presents an example of the ArrayList with the Objects of multiple types.
No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.
ArrayLists can only hold objects like String and the wrapper classes Integer and Double. They cannot hold primitive types like int, double, etc.
It's called "boxing": automagically the int is converted to a reference type. This does cost some performance.
See also Boxing and Unboxing.
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