Friday, January 19, 2018

How to use Java List Interface and ArrayList with example

What is a list?
Java List is a sub interface of Java Collection. It is an ordered collection of objects with methods to add, modify and delete objects. List allows duplicates. Objects/data can be accessed using index notation. 
Actual implementation of List interface is provided by ArrayList, LinkedList, Vector and Stack classes. We will see an example of List interface with ArrayList implementation. 

Difference between Array and List 
Array is fixed length data structure, One cannot change the length after creating the Array object whereas List is dynamic in size. As elements are added to an ArrayList its capacity grows automatically. Arrays store homogeneous type of data, whereas List can store heterogeneous data or objects.  

Use Case 
We will see an example of List’s ArrayList implementation in which we will create a customer object and add few customers to an ArrayList and print out object data by iterating over the list. We will use eclipse IDE for this demo. First create a Java Project and create a Customer class which is a POJO class as follows.
package com.listdemo.org;
 public class Customer {
       private String name;
       private int age;
       private String gender;
       private String address;
       private String phone;
       public Customer(String name, int age, String gender, String address,
                     String phone) {
              super();
              this.name = name;
              this.age = age;
              this.gender = gender;
              this.address = address;
              this.phone = phone;
       }
    }
       public void setName(String name) {
              this.name = name;
       }
       public int getAge() {
              return age;
       }
       public void setAge(int age) {
              this.age = age;
       }
       public String getGender() {
              return gender;
       }
       public void setGender(String gender) {
              this.gender = gender;
       }
       public String getAddress() {
              return address;
       }
       public void setAddress(String address) {
              this.address = address;
       }
       public String getPhone() {
              return phone;
       }
       public void setPhone(String phone) {
              this.phone = phone;
       }  
}

In the above class we are just defining the customer class with few attributes and their getter and setter methods. We are also defining a constructor with all the fields. Next we will create a main class and create some customers as follows

package com.listdemo.org;
public class Main {
       public static void main(String[] args) {
             Customer customer1 = new Customer("Tushar", 34, "Male", "Indore", "9282838839");
              Customer customer2 = new Customer("Vikas", 31, "Male", "Nagpur", "923838839");
              Customer customer3 = new Customer("Rakesh", 33, "Male", "Ahmedabad", "9232838839");
              Customer customer4 = new Customer("Mayank", 35, "Male", "Gwalior", "9282832339");
             }
}

Next we will create a list with ArrayList implementation and define its type as customer which means that we want this list to hold Customer objects. We will need to import the ArrayList class and List interface.

import java.util.ArrayList;
import java.util.List;

List<Customer> customerList = new ArrayList<Customer>();           


Next we will add customers to the customer list as follows.

customerList.add(customer1);
             customerList.add(customer2);
             customerList.add(customer3);
             customerList.add(customer4);

Now to iterate over the list, we can use for loop with following variation

for(Customer c:customerList)
              {
                     System.out.println(c.getName());
                     System.out.println(c.getGender());
                     System.out.println(c.getAddress());
                     System.out.println(c.getAge());
                     System.out.println("=======================================================");
                    
              }

In the above code snippet we are iterating over the customer list and printing each object attributes. 
The complete code is as follows:
package com.listdemo.org;

import java.util.ArrayList;
import java.util.List;

public class Main {

       /**
        * @param args
        */
       public static void main(String[] args) {
             
              Customer customer1 = new Customer("Tushar", 34, "Male", "Indore", "9282838839");
              Customer customer2 = new Customer("Vikas", 31, "Male", "Nagpur", "923838839");
              Customer customer3 = new Customer("Rakesh", 33, "Male", "Ahmedabad", "9232838839");
              Customer customer4 = new Customer("Mayank", 35, "Male", "Gwalior", "9282832339");
             
             
              List<Customer> customerList = new ArrayList<Customer>();
             
              customerList.add(customer1);
              customerList.add(customer2);
              customerList.add(customer3);
              customerList.add(customer4);
             
              for(Customer c:customerList)
              {
                     System.out.println(c.getName());
                     System.out.println(c.getGender());
                     System.out.println(c.getAddress());
                     System.out.println(c.getAge());
                     System.out.println("=======================================================");
                    
              }

       }

}
After we run the application, we get the following output
Tushar
Male
Indore
34
=======================================================
Vikas
Male
Nagpur
31
=======================================================
Rakesh
Male
Ahmedabad
33
=======================================================
Mayank
Male
Gwalior
35
=======================================================

To remove an item from the list, we can use the following method.


customerList.remove(customer3);

This will remove customer3 from the list. We can also use the index 2 to remove customer3 as follows


customerList.remove(2);

Lists are the most widely used data structure in Java and understanding how to use it is key to do effective development. Hope this tutorial gave you good insights into how List works in Java. 

Complete codebase can be found here

Get Code

No comments:

Post a Comment