📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Difference between Array and ArrayList in Java
Fixed Size vs Dynamic Size
int[] numbers = new int[5]; // Array of size 5
// Adding elements to the array
numbers[0] = 1;
numbers[1] = 2;
// We can't add more than 5 elements, doing so will result in ArrayIndexOutOfBoundsException.
ArrayList<Integer> numbersList = new ArrayList<>(); // ArrayList
// Adding elements to the ArrayList
numbersList.add(1);
numbersList.add(2);
// We can keep adding elements, the ArrayList grows automatically.
Type: Primitives vs Objects
int[] intArray = new int[5]; // Array with primitive type
ArrayList<Integer> intArrayList = new ArrayList<>(); // ArrayList with object type
Performance
Flexibility
ArrayList is more flexible because it comes with built-in methods for adding, removing, and querying elements provided by the Collection API, whereas with arrays, you have to manually code these functionalities.ArrayList.add() method:
List<String> animals = new ArrayList<>(); // Adding new elements to the ArrayList animals.add("Lion"); animals.add("Tiger");
// initialize primitive one dimensional array int[] anArray = new int[5]; anArray[0] = 10; // initialize first element anArray[1] = 20; // initialize second element anArray[2] = 30; // and so forth
Usage:
Array and ArrayList Example
public class ArrayArrayListExample {
public static void main(String[] args) {
// Creating an ArrayList of String using
List<String> animals = new ArrayList<>();
// Adding new elements to the ArrayList
animals.add("Lion");
animals.add("Tiger");
animals.add("Cat");
animals.add("Dog");
System.out.println(animals);
String[] arrayOfAnimals = new String[4];
System.out.println(arrayOfAnimals.length);
arrayOfAnimals[0] = "Lion";
arrayOfAnimals[1] = "Tiger";
arrayOfAnimals[2] = "Cat";
arrayOfAnimals[3] = "Dog";
for (String string : arrayOfAnimals) {
System.out.println(string);
}
}
}
[Lion, Tiger, Cat, Dog]
4
Lion
Tiger
Cat
Dog
how can you say that arrays is unordered
ReplyDeleteUnordered : Both does not guarantee ordered elements.
You are correct, Array and ArrayList preserve the insertion order. This point may be removed.
Delete