How to Add and Remove Elements from an Dynamic Array in Java?

Java beginners often ask how to add new elements to an array in Java? or how to remove elements from an array in Java? is that possible in Java? Well, no, it's not possible in Java because arrays length cannot be changed once created. This means neither you can add new elements nor you can remove an old one from an array in Java. All you can do is reassign values to a different bucket. For example, if you have a string array of length 3 like {"java", "is", "great"} then you can just replace the individual index to make it like {"Python", "is", "great"} by replacing "java" with "Python" at first index, but you cannot add or remove elements.

An important thing to remember is that when we say we add an element into an array, we mean that it's length increased by one and when deleting an element, it's length should go down by 1, which is not possible because the length of the array is constant and cannot be changed once created. That's also the main difference between an array and linked list data structure.

Then the bigger question comes? What do we do? if we have an array of active users and new user logs in how do we store that into an array? how do we remove a user when he logs out.

Well, you can use ArrayList instead of an array, which allows you to add or remove elements. It's like a dynamic array that can grow and shrink in size if needed. In this article, I will show you how to add and remove elements from an ArrayList in Java.

Btw, If you are a beginner then you should go through a comprehensive course like The Complete Java Master Class for Beginners to learn about essential classes from JDK, especially the Java Collection Framework.




How to add and remove Objects from ArrayList in Java

Here is a code example to add and remove elements from an ArrayList in Java:

import java.util.ArrayList;

public class Helloworld {

  public static void main(String[] args) {

    // create an arraylist
    ArrayList<String> activeUsers = new ArrayList<>();
    System.out.println("ArrayList initially: " + activeUsers);
    // add users using add() method
    activeUsers.add("rohasa");
    System.out.println("ArrayList after adding one element: " + activeUsers);

    activeUsers.add("chibaka");
    System.out.println("ArrayList after adding two elements: " + activeUsers);

    activeUsers.add("sakasia");
    System.out.println("ArrayList after adding three elements: " + activeUsers);

    // remove users using remove() method
    activeUsers.remove("rohasa");
    System.out.println("ArrayList after removing one element: " + activeUsers);

    activeUsers.remove("chibaka");
    System.out.println("ArrayList after removing two elements: " + activeUsers);

    activeUsers.remove("sakasia");
    System.out.println("ArrayList after adding three elements: " + activeUsers);
  }

}
Output
ArrayList initially: []
ArrayList after adding one element: [rohasa]
ArrayList after adding two elements: [rohasa, chibaka]
ArrayList after adding three elements: [rohasa, chibaka, sakasia]
ArrayList after removing one element: [chibaka, sakasia]
ArrayList after removing two elements: [sakasia]
ArrayList after adding three elements: []

From the output, you can see that the ArrayList changes after you add or remove elements. Their size also changes like initially when you create an ArrayList the size is zero but once you add one element is incremented to 1 and goes up to 3 and then you start removing elements its size started to decrease and finally become zero one all elements were removed.

The size() method returns is a number of elements in ArrayList, you can get this by calling the size() method. It's very different from the length of the Array, which never changes after you create the array. You can further check out Java Fundamentals: Collections course on Pluralsight to learn more about essential collection classes in Java-like List, Set, Map, etc. This course is created by Java champion Richard Warburton.



By the way, you would need a Pluralsight membership to join this course which costs around $29 per month or $299 per year (14% discount). I highly recommend this subscription to all programmers as it provides instant access to more than 7000+ online courses to learn any tech skill. Alternatively, you can also use their 10-day-free-pass to watch this course for FREE.

That's all about how to add/remove elements into an array in Java. As I said, it's not possible because the length of the array cannot be changed. Apart from using ArrayList, a kind of dynamic array, only another option you have is to create a new array every time you add or remove an element and copy elements from the old array to the new one, which is not an ideal solution.

It would result in so many temporary array objects. Also copying elements from one array to another is a very expensive operation especially for large arrays. In short, use ArrayList if you need a dynamic array in Java.

Further Learning
The Complete Java Masterclass
Java Fundamentals: The Java Language
Data Structures and Algorithms: Deep Dive Using Java


Other Java Overloading and Overriding Articles you may like
  1. What is Polymorphism? Method Overloading or Overriding? (answer)
  2. My favorite free courses to learn Java? (free courses)
  3. Can you override a static method in Java? (answer)
  4. Constructor and Method Overloading best practices in Java (best practices)
  5. 10 Java online courses for beginners (best courses)
  6. Can you overload a static method in Java? (answer)
  7. Why Java doesn't support operator overloading? (answer)
  8. Java or Python? which is a better language for beginners (article)
  9. Can you overload or override the main method in Java? (answer)
  10. Rules of method overriding in Java? (answer)
  11. Difference between overriding, overloading, shadowing, and obscuring in Java? (answer)
  12. 19 Method overloading and overriding interview questions? (list)
  13. Difference between method overloading and overriding? (answer)
  14. What is the real use of overloading and overriding? (answer)
  15. What is Constructor overloading in Java? (answer)

Thanks for reading this article so far. If you like the ArrayList tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are keen to learn Java Programming in-depth but looking for free online courses then you can also check out Java Tutorial for Complete Beginners (FREE) course on Udemy. It's completely free and you just need an Udemy account to join this course.

3 comments:

  1. nice tutorial. thank you...!

    ReplyDelete
  2. Misleading title, should say ArrayList instead of array

    ReplyDelete
    Replies
    1. Yes, correct title should be ArrayList but if you need array, you can always convert ArrayList back to array. Thanks for pointing out.

      Delete