BACK 
										
									

List Collection - ArrayList, LinkedList

List • List interface is an ordered collection. • List allows us to store and access elements sequentially. • It extends the Collection interface. • List Interface implemented by: (classes) • ArrayList • LinkedList • Vector • Stack Java ArrayList class • dynamic array. • To store the elements with duplicates. • ArrayList is Similar to array (no size limit) and more flexible. • stored in contiguous memory locations. • Elements can be added and removed anytime. • Belongs to java.util package. • ArrayList allows duplicate elements. • implements the List interface. • Follows insertion order internally. • It inherits the AbstractList class and implements List interface. • Java ArrayList class is non synchronized. • random access. • works on index basis. • provides more features. • easily scalable compared to arrays. • ArrayList is a resizable-array (dynamic in size). • For ArrayList, need not to specify the size during declaration. • ArrayList manipulation takes longer time due to shifting. • ArrayList dynamic growing and shrinking of size • can not create an array list of the primitive types (use wrapper class in such cases). • ArrayList is single-dimensional. • Array has fixed size. • Need to specify the size of the Array. • Array is multi-dimensional. • Array and ArrayList, both allow null values. • import java.util.ArrayList; • import java.util.Iterator; Operations: • Adding element to List • Changing elements • Removing elements • Iterating elements • get elements • add elements in between two numbers • Sorting elements • ArrayList size Creating an ArrayList • Import the java.util.ArrayList package in order to work with ArrayList. Syntax - ArrayList: ArrayList<Type> arrayList= new ArrayList<>(); • Integer arraylist ArrayList<Integer> arrayList = new ArrayList<>(); • String arraylist ArrayList<String> arrayList = new ArrayList<>(); • Generic ArrayList Syntax: ArrayList<String> al=new ArrayList<String>(); 1. ArrayList() constructor for building an empty array list. ArrayList arr = new ArrayList(); 2. ArrayList(Collection c) • constructor for building an array list initialized with the elements from the collection c. • creating an ArrayList arr with elements of collection c, as: ArrayList arr = new ArrayList(c); 3. ArrayList(int capacity) • constructor for building an array list with the specified initial capacity. • Creating an ArrayList with the initial size being N, as: ArrayList arr = new ArrayList(N); Example: Adding the value in ArrayList: al.add("value1"); Example: Retrieving the element from ArrayList: al.get(3); Example: Setting element at 1st index al.set(1, "ABCD"); Example:get method Integer n= list.get(1); System.out.println("at indext 1 number is:"+n); ArrayList • ArrayList class for implementing resizable-arrays functionality. • ArrayList implements List interface of the collections framework. ArrayList Vs Array • Array needs to declare the size of an array before usage. • Array size hard to change, once array size is declared. • use the ArrayList class for creating resizable arrays. • Unlike arrays, arraylists implicitly adjust their capacity. • Grows and shrinks implicitly when we add or remove elements from ArrayList. • That’s why, Arraylists are known as dynamic arrays. Example: public class ArrayListExample{ public static void main(String args[]) { // Creating the ArrayList ArrayList<String> books = new ArrayList<String>(); // Adding a book to the list books.add("Object oriented Java"); books.add("Java Unleashed"); books.add("Java Orielly"); books.add("Java2 Complete Reference"); // Traversing the list through Iterator Iterator<String> itr = books.iterator(); while (itr.hasNext()) { } } } Iterator Methods • hasNext() boolean hasNext() o does not accept any parameter. o returns true if elements in the iteration. o return false if there is no element found in iteration. o If there are no more elements present iteration, generally logic exists the iteration and come out from the loop • next() E next() o does not accept any parameter. o It returns E that is next element in the traversal. o throws the NoSuchElementException in case of no elements in iteration of the collection. • remove() o default void remove() o does not require any parameters. o no return type. o is to remove the last element returned by the iterator traverse. o throws the UnSupportedOperationException when remove is not supported. o throws the IllegalStateException if the next method is not yet called. • forEachRemaining() o default void forEachRemaining o takes one parameter as action. o Action is that is to be performed. o no return type. o performs the particularized operation on all of the left components of the collection until all the components are consumed or the action throws an exception. o throws a NullPointerException when the action is null. Example: Adding between elements: ArrayList<Integer> list = new ArrayList(); list.add(1); list.add(2); list.add(4); System.out.println(list); // insert element 3 list.add(2, 3); System.out.println(list); Example: Size of the list: int sizeOfList = list.size(); System.out.println("The size is :" + sizeOfList); Basic Example of ArrayList (String Type): ArrayList<String> al=new ArrayList<String>(); al.add("Vishwa"); al.add("PVR"); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } Example: Overriding the element: al.set(3, "value3"); //old value in the position 3 will be changed with value3 Traversing can be done of collection elements through: • By Iterator interface. • By for-each loop. • By ListIterator interface. • By for loop. • By forEach() method. • By forEachRemaining() method. Example: Iteration with while loop – hasNext and next methods: while(iterationObject.hasNext()){ //use iterationObject.next(); } Example: while iteration while(iter.hasNext()){ System.out.println(iter.next()); } Iteration with for-each loop: for(datatype obj: collectionObject){ //Use obj } Example: for-each loop for(String obj: al){ System.out.println(obj); } Example: Using Lambda Expression: al.forEach(param->{ System.out.println(param); }); Example: Usage of ArrayList through User-defined Class: class Employee{ String firstName; Employee(String fname){ this.firstName = fname; } } In Main Class: Employee e1=new Employee("Vishwa"); Employee e2=new Employee("PVR"); ArrayList<Employee> al=new ArrayList<Employee>(); al.add(e1);//adding Employee class object al.add(e2); Iterator iter=al.iterator(); while(iter.hasNext()){ Employee e =(Employee)iter.next(); System.out.println(e.firstName); } Sorting ArrayList: //where al consists of values Collections.sort(al); for(String sortedal:al){ // to print the al after sorting System.out.println(sortedal); } Traversing through ListIterator: ListIterator<String> ll = al.listIterator(list.size()); While(ll.hasPrevious()){ System.out.println(ll.previous); } Example: import java.util.ArrayList; class ArrayListExample { public static void main(String[] args){ ArrayList<String> animals = new ArrayList<>(); // Add elements animals.add("BMW"); animals.add("RR"); animals.add("AUDI"); System.out.println("ArrayList: " + animals); } } Output: ArrayList: [BMW, RR, AUDI] Change ArrayList Elements For modifying arraylist elements, set() method is used. For example: import java.util.ArrayList; class ArrayListExample{ public static void main(String[] args) { ArrayList<String> languages = new ArrayList<>(); // add elements in the array list languages.add("Java"); languages.add("HTMl"); languages.add("C++"); System.out.println("ArrayList: " + languages); // change the element of the array list languages.set(2, "C"); System.out.println("Modified ArrayList: " + languages); } } Output ArrayList: [Java, HTML, C++] Modified ArrayList: [Java, HTML, C] Remove ArrayList Elements In order to remove an arraylist element, remove() method is used. For example: import java.util.ArrayList; class ArrayListExample { public static void main(String[] args) { ArrayList<String> animals = new ArrayList<>(); // add elements in the array list animals.add("lion"); animals.add("tiger"); animals.add("elephant"); System.out.println("ArrayList: " + animals); // remove element from index 2 String str = animals.remove(2); System.out.println("Modified ArrayList: " + animals); System.out.println("Removed Element: " + str); } } Output ArrayList: [lion, tiger, elephant] Updated ArrayList: [lion, tiger] Removed Element: elephant To remove all the arraylist elements at once use: • Java ArrayList removeAll() • Java ArrayList clear() For-each: import java.util.ArrayList; import java.util.Iterator; public class ArrayListExample{ public static void main(String args[]) { // Creating the ArrayList ArrayList<String> books = new ArrayList<String>(); // Adding a book to the list books.add("Object oriented Java"); books.add("Java Unleashed"); books.add("Java Orielly"); books.add("Java2 Complete Reference"); books.add("Java Unleashed"); // Traversing the list through Iterator //Iterator<String> itr = books.iterator(); //while (itr.hasNext()) { //} for(String b:books) } Example with Class and Objects: import java.util.ArrayList; import java.util.Iterator; class Employee{ int eno; String fullname; int sal; Employee(int eno,String fullname,int sal){ this.eno=eno; this.fullname=fullname; this.sal=sal; } } public class ArrayListExample{ public static void main(String args[]) { Employee s1=new Employee(1,"Vishwanath Arabati",98765); Employee s2=new Employee(2,"PVR",98766); Employee s3=new Employee(3,"Sam",98767); //creating arraylist ArrayList<Employee> arrayList=new ArrayList<Employee>(); arrayList.add(s1);//adding Student class object arrayList.add(s2); arrayList.add(s3); //Getting Iterator Iterator itr=arrayList.iterator(); //traversing elements of ArrayList object while(itr.hasNext()){ Employee st=(Employee)itr.next(); System.out.println(st.eno+" "+st.fullname+" "+st.sal); } } } Serialization FileOutputStream fos=new FileOutputStream("employee.txt"); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(arrayList); fos.close(); oos.close(); Deserialization FileInputStream fis=new FileInputStream("employee.txt"); ObjectInputStream ois=new ObjectInputStream(fis); ArrayList list=(ArrayList)ois.readObject(); Remove: arrayList.remove("Java Unleashed"); System.out.println("After remove method: "+ arrayList); //Position basis Removing element arrayList.remove(0); System.out.println("After remove method: "+ arrayList); Sorting: import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; public class ArrayListExample{ public static void main(String args[]) { ArrayList<String> listOfCars = new ArrayList<>(); listOfCars.add("BMW"); listOfCars.add("AUDI"); listOfCars.add("RR"); listOfCars.add("VW"); // Original unsorted list System.out.println("Before Sorting: "+ listOfCars); //Sorting the ArrayList using sort() method Collections.sort(listOfCars); // Printing sorted ArrayList System.out.println("After Sorting: "+ listOfCars); } } Reverse Order: import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; public class ArrayListExample{ public static void main(String args[]) { ArrayList<String> listOfCars = new ArrayList<>(); listOfCars.add("BMW"); listOfCars.add("AUDI"); listOfCars.add("RR"); listOfCars.add("VW"); // Original unsorted list System.out.println("Before Sorting: "+ listOfCars); //Sorting the ArrayList using sort() method Collections.sort(listOfCars); // Printing sorted ArrayList System.out.println("After Sorting: "+ listOfCars); // Sorting the list in descending order Collections.sort(listOfCars, Collections.reverseOrder()); System.out.println("After Sorting: "+ listOfCars); } } • use Collections.sort() method to sort a simple array list. • if the ArrayList is of custom object type then we have two options for sorting: o comparable o comparator interfaces. String Type Sorting: import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; public class ArrayListExample{ public static void main(String args[]) { ArrayList<String> al=new ArrayList<String>(); al.add("Rohit"); al.add("Kohli"); al.add("Jadeja"); al.add("Bumrah"); Collections.sort(al); for(String str: al){ } } } Wrapper Classes Type: import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; class Employee{ int eno; String fullname; int sal; Employee(int eno,String fullname,int sal){ this.eno=eno; this.fullname=fullname; this.sal=sal; } } public class ArrayListExample{ public static void main(String args[]) { ArrayList al=new ArrayList(); al.add(Integer.valueOf(201)); al.add(Integer.valueOf(101)); //internally converted into objects as Integer al.add(230); Collections.sort(al); Iterator itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Example: ArrayList with Integer Values: import java.util.List; import java.util.ArrayList; class ArrayListExample { public static void main(String[] args) { // Creating list using the ArrayList class List<Integer> numbers = new ArrayList<>(); // Add elements to the list numbers.add(1); numbers.add(2); BACK