Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Storing" value types inside an ArrayList

Tags:

c#

.net

arraylist

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?
like image 384
Birdman Avatar asked Dec 01 '11 13:12

Birdman


People also ask

Can an ArrayList 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 do you add different data types in ArrayList?

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.

Can ArrayLists hold multiple data types?

No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.

What data types can ArrayLists hold?

ArrayLists can only hold objects like String and the wrapper classes Integer and Double. They cannot hold primitive types like int, double, etc.


1 Answers

It's called "boxing": automagically the int is converted to a reference type. This does cost some performance.

See also Boxing and Unboxing.

like image 105
Hans Kesting Avatar answered Oct 19 '22 09:10

Hans Kesting