In Java programming, there are two ways to create an array.
Array
: Is a simple fixed-size data structure which requires a size at the time of creation.
ArrayList
: Is a dynamic sized data structure which doesn’t require a specific size at the time of initialization.
Array
An Array
can contain both primitive data types or objects of a class depending on the definition of the array. But it has a fixed size.
// Importing the required librariesimport java.util.Arrays;class Array{public static void main(String args[]){/* ...........Array............. */// Fixed size.// Cannot add more than 3 elements.int[] arr = new int[3];arr[0] = 5;arr[1] = 6;arr[2] = 10;// PrintingSystem.out.println(Arrays.toString(arr));}}
ArrayList
An ArrayList
can’t be created for primitive data types. It only contains an object. It has the ability to grow and shrink dynamically.
int
| Integer
|
| short
| Short
|
| byte
| Byte
|
| char
| Character
|
| float
| Float
|// Importing required librariesimport java.util.ArrayList;class Array_List{public static void main(String args[]){/*............ArrayList..............*/// Variable size.// Can add more elements.ArrayList<Integer> arr = new ArrayList<Integer>();arr.add(5);arr.add(9);arr.add(11);// PrintingSystem.out.println(arr);}}
Free Resources