2

How to add objects to an ArrayList

[Social9_Share type="horizontal"]

How to add user defined objects to an ArrayList ?

ArrayList is from java.util package. This is like an expandable array. Whenever elements are added, the list will expand and when you remove elements the list will shrink.

To add elements to an ArrayList, we have to use void add(Object o) method. To start with,we will add String objects to an ArrayList. We will use generics for type safety. Use String on both sides while declaring ArrayList to work with java 6.
ArrayList<String> names = new ArrayList<>()
Rest of the coding is the same.

The below code works for Java 1.7.

The complete program is given below.

Now, lets us see how to add user defined objects to an ArrayList. For this we need two classes Student and Test.
First,
  • Create the Student class having three instance variables – name, studentId, department
  • Add a parameterised constructor and getter, setter methods for the instance variables
  • Generate toString() method


Next,

  • Create the Test class having main method.
  • Create three student objects and add it to the ArrayList
  • Use a foreach or an iterator to iterate and print the values.

Create the student object either using a parameterised constructor or with a default constructor and then providing values using setter methods.

Next, add the objects to the ArrayList

Now, use a for-each or iterator to print the elements of the ArrayList

Using for-each

Using Iterator

The complete example is given below

You can also use a Scanner to get user input and then add the values to the student object.The modified code is given below

Thats all.
Happy Coding.

Comments(2)

  1. Reply
    Sanju says

    You r blogs in Java are good. Please share how to add user defied objects to a Map

Post a comment