ArrayList:
ArrayList implements the List interface. It uses the Array data structure to store elements. It is dynamic in nature and can increase or decrease the size when required. This is the reason why ArrayList is preferred over Arrays.
There are 3 different ways of creating an ArrayList. They are:
1. public ArrayList(): It creates an empty list with initial capacity 10.
2. public ArrayList(int initialSize): It creates an empty list with the specified initial capacity.
3. public ArrayList(Collection c): It creates a list initialised with the elements of the specified collection.
The syntax of creating an ArrayList object is-
ArrayList<ObjectType> objName = new ArrayList<ObjectType>();
An example of creation of ArrayList of type String is-
ArrayList<String> names = new ArrayList<String>();
The elements in an ArrayList always have to be objects. Thus, if we want to create an ArrayList of integers, we use Integer instead of int, Double instead of double, and so on.
ArrayList<Integer> numbers = new ArrayList<Integer>();
Apart from the methods inherited from the List interface, ArrayList contains other methods. Let us now take a look at some of the most important and frequently used methods.
1. void add(): This method is used to add elements to the ArrayList. This method adds elements to the end of the ArrayList by default. Let’s add names to our ArrayList names that we created above-
names.add("Harry");
names.add("Hermione");
names.add("Ron");
names.add("Ginny");
names.add("Malfoy");
We can also add elements at specified locations in the ArrayList-
names.add(3,"Tom");
2. boolean addAll(Collection C): It adds all the elements of the Collection C to the end of the ArrayList in the order specified by the iterator.3. Object get(int index): It is used to access the element at the specified index. Example-
names.get(1); // Hermione
names.get(5); // Tom
4. boolean contains(): This method checks whether the ArrayList contains the specified element or not. Example-
names.contains("Ginny"); // true
names.contains("Riddle"); // false
5. int size(): This method returns the size of the ArrayList.
names.size(); // 6
6. void ensureCapacity(int requiredCapacity): This method is used to increase the capacity of the ArrayList, if necessary, to ensure that the ArrayList can hold at least the number of elements specified in the argument.
7. void remove(): This method is used to remove specific elements from the ArrayList.
· void remove(int index): Removes element from the specified index. Example: names.remove(3); // Ginny will be removed
· void remove(objectType element): Removes the first occurance of the element in from the ArrayList. Example: names.remove(“Tom”); // Tom will be removed
· void removeAll(): Removes all the occurrences of the element from the ArrayList.
8. void set(int index, ObjectType element): This method is used to update an element from the specified index. Example – names.set(0, “Potter”); // Harry will be replaced by Potter
9. sort(): The Collection interface provides a method sort() to arrange the elements in ascending order. An example of the sort method used in ArrayList is-
Collections.sort(names); //sorts ArrayList in alphabetical order
10. int indexOf(ObjectType element): This method is used to return the index of the element specified in the argument. Example: names.indexOf(“Ron”); // will return 2
11. boolean isEmpty(): This method is used to check if the ArrayList is empty or not.
12. clear(): This method is used to remove all the elements from the ArrayList.
13. Object[] toArray(): This method returns an array containing all of the elements in the ArrayList in the correct order. Throws NullPointerException if the specified array is null.
14. void trimToSize(): Trims the capacity of the ArrayList instance to its current size. This helps in saving memory.
Printing the ArrayList
There are many ways to print the ArrayList.
1. Using iterator interface: We can use an object of Iterator to iterate through the ArrayList. Example-
Iterator itr = names.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
2. Using for loop or while loop: We can use any loop and the get() to traverse through the elements of the ArrayList. Example-
for(int i = 0; i<names.size(); i++)
System.out.println(names.get(i));
3. Using a for-each loop for traversal: Example-
for(String i : names)
System.out.println(i);
Example Program:
/*Declaring ArrayList
//Homogeneous data(same data type)
ArrayList <integer> al = new ArrayList<integer>();
ArrayList <String> al = new ArrayList<String>();
List al = new ArrayList();
*/
//Heterogeneous data(all datatypes)
ArrayList al = new ArrayList();
//Add new elements to the arraylist
al.add(100);
al.add("welcome");
al.add(15.5);
al.add('A');
al.add(true);
System.out.println(al);
//checking the size
System.out.println("Number of elements in arraylist:"+al.size());
//remove
al.remove(1); // here 1 is the index
//al.remove("welcome"); // here welcome is element
System.out.println("After removing element in arraylist:"+al);
//insert a new element
//syntax:add(index,object)
al.add(2,"Python");
System.out.println("After inserting element in arraylist:"+al);
//retreive specific element
System.out.println(al.get(2)); // here 2 is index of element/object
//change/replace element
al.set(2, "C#");
System.out.println("After replacing element in arraylist:"+al);
//search-contains()- it will return true/false
System.out.println(al.contains("C#"));// true
System.out.println(al.contains("C++"));// false
//is Empty()
System.out.println(al.isEmpty());// false
//for reading elements in 3 ways
//1. for loop
/*System.out.println("Reading elements using for loop:");
for(int i=0;i<al.size();i++) {
System.out.println(al.get(i));
}
//2.for..each loop
System.out.println("Reading elements using for.. each loop:");
for(Object e:al) {
System.out.println(e);
}*/
//3. iterator()
System.out.println("Reading elements using iterator method:");
Iterator it = al.iterator();
while(it.hasNext())
{
}
}}
OutPut:
[100, welcome, 15.5, A, true]
Number of elements in arraylist:5
After removing element in arraylist:[100, 15.5, A, true]
After inserting element in arraylist:[100, 15.5, Python, A, true]
Python
After replacing element in arraylist:[100, 15.5, C#, A, true]
true
false
false
Reading elements using iterator method:
100
15.5
C#
A
true
Program for Additional methods performed used in ArrayList
package Collectiondemos;
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListDemo2 {
public static void main(String[] args) {
ArrayList al = new ArrayList();
//Add new elements to the arraylist
al.add('X');
al.add('Y');
al.add('Z');
al.add('A');
al.add('B');
al.add('C');
ArrayList al_dup = new ArrayList();
al_dup.addAll(al);
System.out.println(al_dup);
//Remove all elements
al_dup.removeAll(al_dup);
System.out.println("After removing : "+al_dup);
//Sort ----we use collections(syntax is collections.sort()
System.out.println("Elements in the array list : "+al);
Collections.sort(al);
System.out.println("Elements in the array list after sorting : "+al);
//now sort in reverse order
Collections.sort(al,Collections.reverseOrder());
System.out.println("Elements in the array list after sorting in reverse order : "+al);
//Shuffle- Collections.shuffle()
Collections.shuffle(al);
System.out.println("Elements in the array list after Shuffling : "+al);
}
}
OutPut:
[X, Y, Z, A, B, C]
After removing : []
Elements in the array list : [X, Y, Z, A, B, C]
Elements in the array list after sorting : [A, B, C, X, Y, Z]
Elements in the array list after sorting in reverse order : [Z, Y, X, C, B, A]
Elements in the array list after Shuffling : [A, C, X, Y, B, Z]
LinkedList:
Linked List is a sequence of links which contains items. Each link contains (nodes)a connection to another link.
Syntax: Linkedlist object = new Linkedlist();
Java Linked List class uses two types of Linked list to store the elements:
Singly Linked List
Doubly Linked List
Singly Linked List: In a singly Linked list each node in this list stores the data of the node and a pointer or reference to the next node in the list.
Doubly Linked List: In a doubly Linked list, it has two references, one to the next node and another to previous node.
Available Methods:
Example Program:
package Collectiondemos;
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListDemo1 {
public static void main(String[] args) {
/*Declaring LinkedList
//Homogenous data(same data type)
LinkedList <integer> l = new LinkedList<integer>();
LinkedList <String> l = new LinkedList<String>();
*/
//Heterogeneous data(all datatypes)
LinkedList l = new LinkedList();
//Add new elements to the LinkedList
l.add(100);
l.add("welcome");
l.add(15.5);
l.add('A');
l.add(true);
l.add(null);
System.out.println(l);
//checking the size
System.out.println("Number of elements in LinkedList:"+l.size());
//remove
l.remove(3); // here 3 is the index
System.out.println("After removing , new List:"+l);
//insert a new element
//syntax:add(index,object)
l.add(3,"Java");
System.out.println("After inserting element in LinkedList:"+l);
//retreive specific element
System.out.println(l.get(3)); // here 3 is index of element/object.
//change/replace element
l.set(5, "X");
System.out.println("After replacing element in LinkedList:"+l);
//search-contains()- it will return true/false
System.out.println(l.contains("Java"));// true
System.out.println(l.contains("Python"));// false
//is Empty()
System.out.println(l.isEmpty());// false
//for reading elements in 3 ways
//1. for loop
/*System.out.println("Reading elements using for loop:");
//1. for loop
/*System.out.println("Reading elements using for loop:");
for(int i=0;i<l.size();i++) {
System.out.println(al.get(i));
}
//2.for..each loop
System.out.println("Reading elements using for.. each loop:");
for(Object e:l) {
System.out.println(e);
}*/
//3. iterator()
System.out.println("Reading elements using iterator method:");
Iterator it = l.iterator();
while(it.hasNext())
{
}
} }
Output:
[100, welcome, 15.5, A, true, null]
Number of elements in LinkedList:6
After removing , new List:[100, welcome, 15.5, true, null]
After inserting element in LinkedList:[100, welcome, 15.5, Java, true, null]
Java
After replacing element in LinkedList:[100, welcome, 15.5, Java, true, X]
true
false
false
Reading elements using iterator method:
100
welcome
15.5
Java
true
X
Program for Additional methods performed in LinkedList
package Collectiondemos;
import java.util.LinkedList;
public class LinkedListDemo3 {
public static void main(String[] args) {
LinkedList l = new LinkedList();
//Add new elements to the LinkedList
l.add("dog");
l.add("dog");
l.add("cat");
l.add("horse");
System.out.println(l);
//adding first and last element
l.addFirst("Tiger");
l.addLast("Elephant");
System.out.println("after adding first and last element "+l);
//get method to get the first and last element in list
System.out.println("first and last elementin list :"+l.getFirst());
System.out.println(l.getLast());
//removing first and last element from list
l.removeFirst();
l.removeLast();
System.out.println("After removing first and last element from list: "+l);
}
}
output:
[dog, dog, cat, horse]
after adding first and last element [Tiger, dog, dog, cat, horse, Elephant]
first and last elementin list :Tiger
Elephant
After removing first and last element from list: [dog, dog, cat, horse]
Conclusion:
Use ArrayList when you need fast random access and don't need to do a lot of insertion and deletion.
Use LinkedList when you need fast insertion and deletion and don't need to do a lot of random access.
Keep learning and growing..
Comments