The ArrayList class implements a growable array of objects. 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). They are used when there is a usage of the primitive data types in java structures that require objects such as JLists, ArrayLists. Now, in order to hold primitive data such as int and char in ArrayList are explained.
Primitive data types cannot be stored in ArrayList but can be in Array. ArrayList is a kind of List and List implements Collection interface. The Collection container expects only Objects data types and all the operations done in Collections, like iterations, can be performed only on Objects and not Primitive data types. An ArrayList cannot store ints. To place ints in ArrayList, we must convert them to Integers. This can be done in the add() method on ArrayList. Each int must be added individually.
- Integers in ArrayList
- Character in ArrayList
Case 1: Integers in ArrayList
To place int in ArrayList, First, they are converted into Integers. This can be done in the add method on ArrayList. Each int must be added individually. For example, consider an int array. It has 3 values in it. We create an ArrayList and add those int as Integers in a for-loop.
The add() method receives an Integer. And we can pass an int to this method—the int is cast to an Integer.
[-3, 0, 100] 3 3
Using toArray method – The toArray method copies an ArrayList’s elements to an array.
One returns an Object array and requires casting. This version, though, returns a typed array.
7 8 9
Case 2: Character in ArrayList
In Java ArrayList char character use-case is:
- Convert them into Character
- Convert string value into the character ArrayList.
Example: Java Program to convert a string to a list of characters
[G, e, e, k, s, , f, o, r, , G, e, e, k, s]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.