Java Arraylist Examples

Arraylist implement List interfaces. Arraylist have the capabilities to grow if we added element and there is no space in arraylist and shrink if we remove element from the arraylist . Arraylist have predefined functionalities so developer preferred arraylist over array in java.We can access element by index in arraylist . In arraylist we can add duplicate element. it is allow to store null values also. Arraylist can be grow or shrink as per requirement so it is called dynamic array or resizable array.

ArrayList Features In Java

Inherits – ArrayList inherits AbstractList class and implements List interface.
Index based – Arraylist Elements can be randomly accessed using index . Arraylist Index start with ‘0’.
Ordered – Arraylist Elements maintain insertion ordered .
Dynamic resizing – ArrayList increase size dynamically when more elements needs to be added than it’ current size.
Non synchronized – ArrayList is not synchronized, by default..
Duplicates allowed – We can add duplicate elements in arraylist.
null value  – Arraylist can store null values.
Wrapper class  – ArrayList can not be used for primitive types, like int,float, char, etc. We need a wrapper class for arraylist.                                                                                                Sort – Element is not sorted by default in arraylist.

How ArrayList Works in Java?

Arraylist in java is a dynamic array backing by a array.This backing array is shared by all operation of arraylist. When we add element in arraylist actually element added in this backing array.If there is not enough space to store element in arraylist. it will create new array with doble size and copy all element in this from previous now array and then add new element.

private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; 

    /**
     * The size of the ArrayList
     *
     * @serial
     */
    private int size;

Why ArrayList is better than Array?

Arraylist vs array question ask in many interview. Arraylist provide a lot of functionalities over array .Array have fixed size and can not increase dynamically if there is need during of execution . But in case of arraylist it can increase their size if needed .So we can say array is fixed in size and arraylist is dynamic or re sizable array .Second , arraylist  provide a lot of predefined method for different functionalities so it make developer work easy because these method well efficient.

How to create an ArrayList?

We can create arraylist by using Constructor.
1. ArrayList() : This Constructs create an empty list with an initial capacity of ten.
2. ArrayList(Collection<? extends E> c) :  This Constructs take list containing the elements of the specified collection, in the order they are returned by the collection’s iterator.
3. ArrayList(int initialCapacity) : This Constructs an empty list with the specified initial capacity.
Now we will create arraylist using these constructs .
creating arraylist example:
List<Integer> listOfint = new ArrayList<Integer>();
List<Integer> listWithInitCap = new ArrayList<Integer>(5);
Set<String> set = new HashSet<String>();
List<String> listFromCollection = new ArrayList<String>(set);
In the above example, we have used Integer not int. It is because we cannot use primitive types while creating an arraylist. Instead, we have to use the corresponding wrapper classes. Integer is the corresponding wrapper class of int.

How to add elements to an ArrayList?

we can add element in arraylist using add() method. We have different prototype of add method in arraylist as per below.
add(E e) – This method add the specified element to the end of this list.
add(int index, E element) – This method Inserts the specified element at the specified position in this list.
addAll(Collection<? extends E> c) – This method Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator.
addAll(int index, Collection<? extends E> c) – This method Inserts all of the elements in the specified collection into this list, starting at the specified position.
Let’s write code these method.
import java.util.ArrayList;
import java.util.List;

public class ArrayListAdd {
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("amit");
		list.add("shubham");
		list.add("shivam");
		System.out.println("list ="+list);
		list.add(1, "anup");
		System.out.println("list ="+list);
 	}
}
Output:
list =[amit, shubham, shivam]
list =[amit, anup, shubham, shivam]

How  to Iterating over an ArrayList ?

We can iterate arraylist by using
1. For loop
2. forEach loop
3. Iterator
Let’s try these with code exmple:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListAdd {
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("amit");
		list.add("shubham");
		list.add("shivam");
       //using for loop
		System.out.println("=========>> iterate arraylist using loop");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i));
		}
		//using forEach 
		System.out.println("=======>> iterate arraylist using forEach");
		for (String element : list) {
			System.out.println(element);
		}
		
		//using iterate()
		System.out.println("=======>> iterate ararylist using iterator()");
		Iterator<String> listIterator = list.iterator();
                  while (listIterator.hasNext()) {
                         String element = listIterator.next();
                         System.out.println(element);
                }
 	}
}
Output:
=========>> iterate arraylist using loop
amit
shubham
shivam
=======>> iterate arraylist using forEach
amit
shubham
shivam
=======>> iterate ararylist using iterator()
amit
shubham
shivam

How to Change an element in ArrayList

We can change element of arraylist using set() method. In set method we pass value with index on which position we want to change values. Let’s see this by example

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

public class ChangeElement {
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("amit");
		list.add("shubham");
		list.add("shivam");
		//display list 
		System.out.println("before changing element list is ="+ list);
		//change element on index 1 
		list.set(1, "kapil");
		//display list
		System.out.println("after changing element list is ="+ list);
	}

}

Output:

before changing element list is =[amit, shubham, shivam]
after changing element list is =[amit, kapil, shivam]

How to remove elements from ArrayList?

We can remove element from arraylist using remove(int index) method.Now will learn by using code

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

public class RemoveElementFromArraylist {
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("amit");
		list.add("ravi");
		list.add("shubham");
		list.add("shivam");
		System.out.println("before remove element from list ="+ list);
		list.remove(1);
		System.out.println("after remove element from list ="+ list);
	}

}
Output:
before remove element from list =[amit, ravi, shubham, shivam]
after remove element from list =[amit, shubham, shivam]

ArrayList Methods

Now we will discuss some important java arraylist methods.                                                    1. 1. 1. add(E e) : This method Appends the givenelement to the end of this list.
2. add(int index, E element) : This method Inserts the given element at the given position in this list.
3. clear() : This method Removes all of the elements from this list.
4. clone() : This Method Returns a shallow copy of this ArrayList instance.
5. contains(Object o) : This Method Returns true if this list contains the given element.
6. get(int index) : This method Returns the element at the given position in this list.
7. indexOf(Object o) : Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.
8. isEmpty() : This method returns true if this list contains no.
9. iterator() . This method returns an iterator over the elements in this list in proper sequence.
10. lastIndexOf(Object o) : This method  returns the index of the last occurrence of the given element in this list, or -1 if this list does not contain the element.
11. listIterator() : This method returns a list iterator over the elements in this list (in proper sequence).
12. listIterator(int index) : this method returns a list iterator over the elements in this list (in proper sequence), starting at the given position in the list.
13. remove(int index) : This method removes the element at the given position in this list.
14. remove(Object o) : This method removes the first occurrence of the given element from this list, if it is present.
15. removeRange(int fromIndex, int toIndex) : This method removes from this list all of the elements  whose index is between fromIndex, inclusive, and toIndex, exclusive
16. set(int index, E element) : This method  replaces the element at the specified position in this list with the specified element.
17. size() : This method returns the number of elements in this list.
18. sort(Comparator<? super E> c) : This method sorts this list according to the order induced by the given  Comparator.
19. subList(int fromIndex, int toIndex) : This method returns a view of the portion of this list between the gievn fromIndex, inclusive, and toIndex, exclusive.
20. toArray() : This method returns an array containing all of the elements in this list in proper sequence (from first to last element).
21. toArray(T[] a) : This method returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
22. trimToSize() : This Method trims the capacity of this ArrayList instance to be the list’s current size.

Java ArrayList Examples

References :                                                                                                                      Java Official Document on Collections

 

Leave a Reply

Your email address will not be published. Required fields are marked *

57 − = 53