Java Collections Framework: A Comprehensive Guide
Java Collections Framework: A Comprehensive Guide
3. Collection interface
4. Iterator interface
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
, Vector, LinkedList
, PriorityQueue
and interfaces
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
2 public Object It returns the element and moves the cursor pointer
next() to the next element.
Iterable Interface
The Iterable interface is the root interface for all the collection classes.
The Collection interface extends the Iterable interface and therefore all
the subclasses of Collection interface also implement the Iterable
interface.
1. Iterator<T> iterator()
Collection Interface
The Collection interface is the interface which is implemented by all the
classes in the collection framework. It declares the methods that every
collection will have. In other words, we can say that the Collection
interface builds the foundation on which the collection framework
depends.
Some of the methods of Collection interface are Boolean add ( Object obj),
Boolean addAll ( Collection c), void clear(), etc. which are implemented by
all the subclasses of Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list
type data structure in which we can store the ordered collection of
objects. It can have duplicate values.
There are various methods in List interface that can be used to insert,
delete, and access the elements from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array
to store the duplicate element of different data types. The ArrayList class
maintains the insertion order and is non-synchronized. The elements
stored in the ArrayList class can be randomly accessed. Consider the
following example.
import [Link].*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Ravi");//Adding object in arraylist
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list
internally to store the elements. It can store the duplicate elements. It
maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.
import [Link].*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
Vector
Vector uses a dynamic array to store the data elements. It is similar to
ArrayList. However, It is synchronized and contains many methods that
are not the part of Collection framework.
import [Link].*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
[Link]("Ayush");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Output:
Ayush
Amit
Ashish
Garima
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data
structure, i.e., Stack. The stack contains all of the methods of Vector class
and also provides its methods like boolean push(), boolean peek(),
boolean push(object o), which defines its properties.
Consider the following example.
import [Link].*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
[Link]("Ayush");
[Link]("Garvit");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
[Link]();
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Output:
Ayush
Garvit
Amit
Ashish
Java ArrayList
Java ArrayList class uses a dynamic array for storing the elements. It is
like an array, but there is no size limit. We can add or remove elements
anytime. So, it is much more flexible than the traditional array. It is found
in the [Link] package. It is like the Vector in C++.
The ArrayList in Java can have the duplicate elements also. It implements
the List interface so we can use all the methods of the List interface here.
The ArrayList maintains the insertion order internally.
o Java ArrayList gets initialized by the size. The size is dynamic in the
array list, which varies according to the elements getting added or
removed from the list.
Constructors of ArrayList
Constructor Description
Methods of ArrayList
Method Description
Iterator()
listIterator()
import [Link].*;
public class ArrayListExample1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Printing the arraylist object
[Link](list);
}
}
Test it Now
Output:
FileName: [Link]
import [Link].*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
[Link]("Mango");//Adding object in arraylist
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Traversing list through Iterator
Iterator itr=[Link]();//getting the Iterator
while([Link]()){//check if iterator has the elements
[Link]([Link]());//printing the element and move to next
}
}
}
Test it Now
Output:
Mango
Apple
Banana
Grapes
FileName: [Link]
1. import [Link].*;
2. public class ArrayListExample4{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. [Link]("Mango");
6. [Link]("Apple");
7. [Link]("Banana");
8. [Link]("Grapes");
9. //accessing the element
10. [Link]("Returning element: "+[Link](1));//it will return t
he 2nd element, because index starts from 0
11. //changing the element
12. [Link](1,"Dates");
13. //Traversing list
14. for(String fruit:al)
15. [Link](fruit);
16.
17. }
18. }
Test it Now
Output:
FileName: [Link]
1. import [Link].*;
2. class SortArrayList{
3. public static void main(String args[]){
4. //Creating a list of fruits
5. List<String> list1=new ArrayList<String>();
6. [Link]("Mango");
7. [Link]("Apple");
8. [Link]("Banana");
9. [Link]("Grapes");
10. //Sorting the list
11. [Link](list1);
12. //Traversing list through the for-each loop
13. for(String fruit:list1)
14. [Link](fruit);
15.
16. [Link]("Sorting numbers...");
17. //Creating a list of numbers
18. List<Integer> list2=new ArrayList<Integer>();
19. [Link](21);
20. [Link](11);
21. [Link](51);
22. [Link](1);
23. //Sorting the list
24. [Link](list2);
25. //Traversing list through the for-each loop
26. for(Integer number:list2)
27. [Link](number);
28. }
29.
30. }
Output:
Apple
Banana
Grapes
Mango
Sorting numbers...
1
11
21
51
Java LinkedList class uses a doubly linked list to store the elements. It
provides a linked-list data structure. It inherits the AbstractList class and
implements List and Deque interfaces.
The important points about Java LinkedList are:
1. import [Link].*;
2. public class LinkedList1{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }
Output: Ravi
Vijay
Ravi
Ajay
1. import [Link].*;
2. public class LinkedList2{
3. public static void main(String args[]){
4. LinkedList<String> ll=new LinkedList<String>();
5. [Link]("Initial list of elements: "+ll);
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ajay");
9. [Link]("After invoking add(E e) method: "+ll);
10. //Adding an element at the specific position
11. [Link](1, "Gaurav");
12. [Link]("After invoking add(int index, E element)
method: "+ll);
13. LinkedList<String> ll2=new LinkedList<String>();
14. [Link]("Sonoo");
15. [Link]("Hanumat");
16. //Adding second list elements to the first list
17. [Link](ll2);
18. [Link]("After invoking addAll(Collection<? extend
s E> c) method: "+ll);
19. LinkedList<String> ll3=new LinkedList<String>();
20. [Link]("John");
21. [Link]("Rahul");
22. //Adding second list elements to the first list at specific positi
on
23. [Link](1, ll3);
24. [Link]("After invoking addAll(int index, Collection
<? extends E> c) method: "+ll);
25. //Adding an element at the first position
26. [Link]("Lokesh");
27. [Link]("After invoking addFirst(E e) method: "+ll)
;
28. //Adding an element at the last position
29. [Link]("Harsh");
30. [Link]("After invoking addLast(E e) method: "+ll)
;
31.
32. }
33. }
Initial list of elements: []
After invoking add(E e) method: [Ravi, Vijay, Ajay]
After invoking add(int index, E element) method: [Ravi, Gaurav, Vijay,
Ajay]
After invoking addAll(Collection<? extends E> c) method:
[Ravi, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addAll(int index, Collection<? extends E> c) method:
[Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addFirst(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat]
After invoking addLast(E e) method:
[Lokesh, Ravi, John, Rahul, Gaurav, Vijay, Ajay, Sonoo, Hanumat, Harsh]
1. import [Link].*;
2. public class LinkedList3 {
3.
4. public static void main(String [] args)
5. {
6. LinkedList<String> ll=new LinkedList<String>();
7. [Link]("Ravi");
8. [Link]("Vijay");
9. [Link]("Ajay");
10. [Link]("Anuj");
11. [Link]("Gaurav");
12. [Link]("Harsh");
13. [Link]("Virat");
14. [Link]("Gaurav");
15. [Link]("Harsh");
16. [Link]("Amit");
17. [Link]("Initial list of elements: "+ll);
18. //Removing specific element from arraylist
19. [Link]("Vijay");
20. [Link]("After invoking remove(object) method:
"+ll);
21. //Removing element on the basis of specific position
22. [Link](0);
23. [Link]("After invoking remove(index) method: "
+ll);
24. LinkedList<String> ll2=new LinkedList<String>();
25. [Link]("Ravi");
26. [Link]("Hanumat");
27. // Adding new elements to arraylist
28. [Link](ll2);
29. [Link]("Updated list : "+ll);
30. //Removing all the new elements from arraylist
31. [Link](ll2);
32. [Link]("After invoking removeAll() method: "+ll
);
33. //Removing first element from the list
34. [Link]();
35. [Link]("After invoking removeFirst() method: "
+ll);
36. //Removing first element from the list
37. [Link]();
38. [Link]("After invoking removeLast() method: "
+ll);
39. //Removing first occurrence of element from the list
40. [Link]("Gaurav");
41. [Link]("After invoking removeFirstOccurrence()
method: "+ll);
42. //Removing last occurrence of element from the list
43. [Link]("Harsh");
44. [Link]("After invoking removeLastOccurrence()
method: "+ll);
45.
46. //Removing all the elements available in the list
47. [Link]();
48. [Link]("After invoking clear() method: "+ll);
49. }
50. }
Initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav, Harsh,
Virat, Gaurav, Harsh, Amit]
After invoking remove(index) method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
Updated list : [Ajay, Anuj, Gaurav, Harsh, Virat, Gaurav, Harsh, Amit,
Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav, Harsh, Virat,
Gaurav, Harsh, Amit]
After invoking removeFirst() method: [Gaurav, Harsh, Virat, Gaurav, Harsh,
Amit]
After invoking removeLast() method: [Gaurav, Harsh, Virat, Gaurav, Harsh]
After invoking removeFirstOccurrence() method: [Harsh, Virat, Gaurav,
Harsh]
After invoking removeLastOccurrence() method: [Harsh, Virat, Gaurav]
After invoking clear() method: []
5) The memory location for the The location for the elements of
elements of an ArrayList is a linked list is not contagious.
contiguous.
Java Vector
Vector is like the dynamic array which can grow or shrink
its size. Unlike array, we can store n-number of elements in
it as there is no size limit. It is a part of Java Collection
framework since Java 1.2. It is found in
the [Link] package and implements the List interface, so
we can use all the methods of List interface here.
S Method Description
N
8) containsAll() It returns true if the vector contains all of the elements in the specifi
9) copyInto() It is used to copy the components of the vector into the specified ar
12) ensureCapacity() It is used to increase the capacity of the vector which is in use
ensures that the vector can hold at least the number of component
minimum capacity argument.
13) equals() It is used to compare the specified object with the vector for equalit
15) forEach() It is used to perform the given action for each element of the
elements have been processed or the action throws an exception.
16) get() It is used to get an element at the specified position in the vector.
18) indexOf() It is used to get the index of the first occurrence of the specifie
vector. It returns -1 if the vector does not contain the element.
19) insertElementAt() It is used to insert the specified object as a component in the giv
specified index.
21) iterator() It is used to get an iterator over the elements in the list in proper se
22) lastElement() It is used to get the last component of the vector.
23) lastIndexOf() It is used to get the index of the last occurrence of the specifie
vector. It returns -1 if the vector does not contain the element.
24) listIterator() It is used to get a list iterator over the elements in the list in proper
25) remove() It is used to remove the specified element from the vector. If the
contain the element, it is unchanged.
26) removeAll() It is used to delete all the elements from the vector that are presen
collection.
27) removeAllElemen It is used to remove all elements from the vector and set the size
ts() zero.
30) removeIf() It is used to remove all of the elements of the collection that
predicate.
31) removeRange() It is used to delete all of the elements from the vector whose i
fromIndex, inclusive and toIndex, exclusive.
32) replaceAll() It is used to replace each element of the list with the result of appl
to that element.
33) retainAll() It is used to retain only that element in the vector which is containe
collection.
34) set() It is used to replace the element at the specified position in the
specified element.
35) setElementAt() It is used to set the component at the specified index of the vecto
object.
37) size() It is used to get the number of components in the given vector.
38) sort() It is used to sort the list according to the order induced by the speci
39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the
list.
40) subList() It is used to get a view of the portion of the list between fromInd
toIndex, exclusive.
41) toArray() It is used to get an array containing all of the elements in this vecto
43) trimToSize() It is used to trim the capacity of the vector to the vector's current si
Output:
ArrayList Vector