Trusted answers to developer questions

Array vs. ArrayList in Java

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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.

svg viewer
svg viewer

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.

Example

// Importing the required libraries
import 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;
// Printing
System.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.

  • Remember that in Java, every primitive data type has a wrapper class. | Primitive | Wrapper class | | — | — | | int | Integer | | short | Short | | byte | Byte | | char | Character | | float | Float |

Example

// Importing required libraries
import 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);
// Printing
System.out.println(arr);
}
}

RELATED TAGS

array
arraylist
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?