0% found this document useful (0 votes)
11 views22 pages

Java Collections Framework Overview

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views22 pages

Java Collections Framework Overview

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Collections in Java

The Collection in Java is a framework that provides an architecture to store


and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

Hierarchy of Collection Framework


Let us see the hierarchy of Collection framework. The [Link] package
contains all the classes and interfaces for the Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as
follows:

No. Method Description

1 public boolean add(E e) It is used to insert an element in this collection.

2 public booleanaddAll(Collection<? It is used to insert the specified collection elements in


extends E> c) the invoking collection.

3 public boolean remove(Object It is used to delete an element from the collection.


element)

4 public booleanremoveAll(Collection<? It is used to delete all the elements of the specified


> c) collection from the invoking collection.

5 default booleanremoveIf(Predicate<? It is used to delete all the elements of the collection


super E> filter) that satisfy the specified predicate.

6 public booleanretainAll(Collection<?> It is used to delete all the elements of invoking


c) collection except the specified collection.

7 public int size() It returns the total number of elements in the


collection.

8 public void clear() It removes the total number of elements from the
collection.

9 public boolean contains(Object It is used to search an element.


element)

10 public It is used to search the specified collection in the


booleancontainsAll(Collection<?> c) collection.

11 public Iterator iterator() It returns an iterator.


12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime
type of the returned array is that of the specified
array.

14 public booleanisEmpty() It checks if collection is empty.

15 default Stream<E>parallelStream() It returns a possibly parallel Stream with the collection


as its source.

16 default Stream<E> stream() It returns a sequential Stream with the collection as its
source.

17 default Spliterator<E>spliterator() It generates a Spliterator over the specified elements


in the collection.

18 public boolean equals(Object It matches two collections.


element)

19 public int hashCode() It returns the hash code number of the collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

No. Method Description

1 public It returns true if the iterator has more elements otherwise it re


booleanhasNext() false.

2 public Object next() It returns the element and moves the cursor pointer to the
element.
3 public void remove() It removes the last elements returned by the iterator. It is less u

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.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.

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.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and


Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete,
and access the elements from the list.

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.
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 class can contain duplicate elements.


o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because the array works on an
index basis.
o In ArrayList, manipulation is a little bit slower than the LinkedList in
Java because a lot of shifting needs to occur if any element is removed
from the array list.
o We can not create an array list of the primitive types, such as int, float,
char, etc. It is required to use the required wrapper class in such cases.
For example:

ArrayList<int> al = ArrayList<int>(); // does not work


ArrayList<Integer> al = new ArrayList<Integer>(); // works fine
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.

ArrayList class declaration


Let's see the declaration for [Link] class.

1. public class ArrayList<E> extends AbstractList<E> implements List<E>, Rando


mAccess, Cloneable, Serializable
2.
Constructors of ArrayList
Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? It is used to build an array list that is initialized with the elements of
extends E> c) the collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.

Methods of ArrayList
Method Description

void add(int index, E element) It is used to insert the specified element at the specified
position in a list.

boolean add(E e) It is used to append the specified element at the end of a list.

boolean addAll(Collection<? extends It is used to append all of the elements in the specified
E> c) collection to the end of this list, in the order that they are
returned by the specified collection's iterator.

boolean addAll(int index, It is used to append all the elements in the specified
Collection<? extends E> c) collection, starting at the specified position of the list.

void clear() It is used to remove all of the elements from this list.

void It is used to enhance the capacity of an ArrayList instance.


ensureCapacity(intrequiredCapacity)

E get(int index) It is used to fetch the element from the particular position of
the list.

booleanisEmpty() It returns true if the list is empty, otherwise false.

Iterator()

listIterator()

intlastIndexOf(Object o) It is used to return the index in this list of the last occurrence
of the specified element, or -1 if the list does not contain this
element.

Object[] toArray() It is used to return an array containing all of the elements in


this list in the correct order.

<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in
this list in the correct order.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It returns true if the list contains the specified element.

intindexOf(Object o) It is used to return the index in this list of the first occurrence
of the specified element, or -1 if the List does not contain this
element.

E remove(int index) It is used to remove the element present at the specified


position in the list.

boolean remove(Object o) It is used to remove the first occurrence of the specified


element.

boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.

booleanremoveIf(Predicate<? super It is used to remove all the elements from the list that
E> filter) satisfies the given predicate.

protected It is used to remove all the elements lies within the given
void removeRange(intfromIndex, range.
inttoIndex)

void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the
operator) specified element.

void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present
in the specified collection.

E set(int index, E element) It is used to replace the specified element in the list, present
at the specified position.

void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of the
specified comparator.

Spliterator<E>spliterator() It is used to create a spliterator over the elements in a list.

List<E>subList(intfromIndex, It is used to fetch all the elements that lies within the given
inttoIndex) range.

int size() It is used to return the number of elements present in the list.

void trimToSize() It is used to trim the capacity of this ArrayList instance to be


the list's current size.

Java Non-generic Vs. Generic Collection


Java collection framework was non-generic before JDK 1.5. Since 1.5, it is
generic.

Java new generic collection allows you to have only one type of object in a
collection. Now it is type-safe, so typecasting is not required at runtime.
Let's see the old non-generic example of creating a Java collection.

1. ArrayList list=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

1. ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist

In a generic collection, we specify the type in angular braces. Now


ArrayList is forced to have the only specified type of object in it. If
you try to add another type of object, it gives a compile-time error.

Java ArrayList Example


FileName: [Link]

1. import [Link].*;
2. public class ArrayListExample1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. [Link]("Mango");//Adding object in arraylist
6. [Link]("Apple");
7. [Link]("Banana");
8. [Link]("Grapes");
9. //Printing the arraylist object
10. [Link](list);
11. }
12.}
Test it Now

Output:

[Mango, Apple, Banana, Grapes]

Iterating ArrayList using Iterator


Let's see an example to traverse ArrayList elements using the Iterator
interface.
FileName: [Link]

1. import [Link].*;
2. public class ArrayListExample2{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. [Link]("Mango");//Adding object in arraylist
6. [Link]("Apple");
7. [Link]("Banana");
8. [Link]("Grapes");
9. //Traversing list through Iterator
10. Iterator itr=[Link]();//getting the Iterator
11. while([Link]()){//check if iterator has the elements
12. [Link]([Link]());//printing the element and move to next
13. }
14. }
15.}
Test it Now

Output:

Mango
Apple
Banana
Grapes

Iterating ArrayList using For-each loop


Let's see an example to traverse the ArrayList elements using the for-each
loop

FileName: [Link]

1. import [Link].*;
2. public class ArrayListExample3{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. [Link]("Mango");//Adding object in arraylist
6. [Link]("Apple");
7. [Link]("Banana");
8. [Link]("Grapes");
9. //Traversing list through for-each loop
10. for(String fruit:list)
11. [Link](fruit);
12.
13. }
14.}

Output:

Test it Now
Mango
Apple
Banana
Grapes

Get and Set ArrayList


The get() method returns the element at the specified index, whereas
the set() method changes the element.

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 the 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:

Returning element: Apple


Mango
Dates
Banana
Grapes

How to Sort ArrayList


The [Link] package provides a utility class Collections, which has the
static method sort(). Using the [Link]() method, we can easily
sort the ArrayList.

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

User-defined class objects in Java ArrayList


Let's see an example where we are storing Student class object in an array
list.

FileName: [Link]

1. class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
[Link]=rollno;
[Link]=name;
[Link]=age;
}
}
1. import [Link].*;
2. class ArrayList5{
3. public static void main(String args[]){
4. //Creating user-defined class objects
5. Student s1=new Student(101,"Sonoo",23);
6. Student s2=new Student(102,"Ravi",21);
7. Student s2=new Student(103,"Hanumat",25);
8. //creating arraylist
9. ArrayList<Student> al=new ArrayList<Student>();
10. [Link](s1);//adding Student class object
11. [Link](s2);
12. [Link](s3);
13. //Getting Iterator
14. Iterator itr=[Link]();
15. //traversing elements of ArrayList object
16. while([Link]()){
17. Student st=(Student)[Link]();
18. [Link]([Link]+" "+[Link]+" "+[Link]);
19. }
20. }
21.}

Output:

101 Sonoo 23
102 Ravi 21
103 Hanumat 25

Java ArrayList example to add elements


Here, we see different ways to add an element.

FileName: [Link]

1. import [Link].*;
2. class ArrayList7{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. [Link]("Initial list of elements: "+al);
6. //Adding elements to the end of the list
7. [Link]("Ravi");
8. [Link]("Vijay");
9. [Link]("Ajay");
10. [Link]("After invoking add(E e) method: "+al);
11. //Adding an element at the specific position
12. [Link](1, "Gaurav");
13. [Link]("After invoking add(int index, E element) method: "+al);
14. ArrayList<String> al2=new ArrayList<String>();
15. [Link]("Sonoo");
16. [Link]("Hanumat");
17. //Adding second list elements to the first list
18. [Link](al2);
19. [Link]("After invoking addAll(Collection<? extends E> c) method
: "+al);
20. ArrayList<String> al3=new ArrayList<String>();
21. [Link]("John");
22. [Link]("Rahul");
23. //Adding second list elements to the first list at specific position
24. [Link](1, al3);
25. [Link]("After invoking addAll(int index, Collection<? extends E>
c) method: "+al);
26.
27. }
28.}

Output:

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]
Java ArrayList example to remove elements
Here, we see different ways to remove an element.

FileName: [Link]

1. import [Link].*;
2. class ArrayList8 {
3.
4. public static void main(String [] args)
5. {
6. ArrayList<String> al=new ArrayList<String>();
7. [Link]("Ravi");
8. [Link]("Vijay");
9. [Link]("Ajay");
10. [Link]("Anuj");
11. [Link]("Gaurav");
12. [Link]("An initial list of elements: "+al);
13. //Removing specific element from arraylist
14. [Link]("Vijay");
15. [Link]("After invoking remove(object) method: "+al);
16. //Removing element on the basis of specific position
17. [Link](0);
18. [Link]("After invoking remove(index) method: "+al);
19.
20. //Creating another arraylist
21. ArrayList<String> al2=new ArrayList<String>();
22. [Link]("Ravi");
23. [Link]("Hanumat");
24. //Adding new elements to arraylist
25. [Link](al2);
26. [Link]("Updated list : "+al);
27. //Removing all the new elements from arraylist
28. [Link](al2);
29. [Link]("After invoking removeAll() method: "+al);
30. //Removing elements on the basis of specified condition
31. [Link](str -> [Link]("Ajay")); //Here, we are using Lambda express
ion
32. [Link]("After invoking removeIf() method: "+al);
33. //Removing all the elements available in the list
34. [Link]();
35. [Link]("After invoking clear() method: "+al);
36. }
37. }

Output:

An initial list of elements: [Ravi, Vijay, Ajay, Anuj, Gaurav]


After invoking remove(object) method: [Ravi, Ajay, Anuj, Gaurav]
After invoking remove(index) method: [Ajay, Anuj, Gaurav]
Updated list : [Ajay, Anuj, Gaurav, Ravi, Hanumat]
After invoking removeAll() method: [Ajay, Anuj, Gaurav]
After invoking removeIf() method: [Anuj, Gaurav]
After invoking clear() method: []

Java ArrayList example of retainAll() method


FileName: [Link]

1. import [Link].*;
2. class ArrayList9{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. [Link]("Ravi");
6. [Link]("Vijay");
7. [Link]("Ajay");
8. ArrayList<String> al2=new ArrayList<String>();
9. [Link]("Ravi");
10. [Link]("Hanumat");
11. [Link](al2);
12. [Link]("iterating the elements after retaining the elements of al2");
13. Iterator itr=[Link]();
14. while([Link]()){
15. [Link]([Link]());
16. }
17. }
18.}

Output:

iterating the elements after retaining the elements of al2


Ravi

Java ArrayList example of isEmpty() method


FileName: [Link]

1. import [Link].*;
2. class ArrayList10{
3.
4. public static void main(String [] args)
5. {
6. ArrayList<String> al=new ArrayList<String>();
7. [Link]("Is ArrayList Empty: "+[Link]());
8. [Link]("Ravi");
9. [Link]("Vijay");
10. [Link]("Ajay");
11. [Link]("After Insertion");
12. [Link]("Is ArrayList Empty: "+[Link]());
13. }
14. }

Output:

Is ArrayList Empty: true


After Insertion
Is ArrayList Empty: false

Java ArrayList Example: Book


Let's see an ArrayList example where we are adding books to the list and
printing all the books.

FileName: [Link]

1. import [Link].*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12.}
13.}
[Link] class ArrayListExample20 {
[Link] static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications and Networking","Forouzan","Mc
Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. [Link](b1);
24. [Link](b2);
25. [Link](b3);
26. //Traversing list
27. for(Book b:list){
28. [Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]
ntity);
29. }
30.}
31.}
Test it Now

Output:
101 Let us C YashwantKanetkar BPB 8
102 Data Communications and Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Size and Capacity of an ArrayList


Size and capacity of an array list are the two terms that beginners find
confusing. Let's understand it in this section with the help of some examples.
Consider the following code snippet.

FileName: [Link]

1. import [Link].*;
2.
3. public class SizeCapacity
4. {
5.
6. public static void main(String[] args) throws Exception
7. {
8.
9. ArrayList<Integer> al = new ArrayList<Integer>();
10.
11. [Link]("The size of the array is: " + [Link]());
12.}
13.}

Output:

The size of the array is: 0

Explanation: The output makes sense as we have not done anything with
the array list. Now observe the following program.

FileName: [Link]

1. import [Link].*;
2.
3. public class SizeCapacity1
4. {
5.
6. public static void main(String[] args) throws Exception
7. {
8.
9. ArrayList<Integer> al = new ArrayList<Integer>(10);
10.
11. [Link]("The size of the array is: " + [Link]());
12.}
13.}

Output:

The size of the array is: 0

Explanation: We see that the size is still 0, and the reason behind this is the
number 10 represents the capacity no the size. In fact, the size represents
the total number of elements present in the array. As we have not added any
element, therefore, the size of the array list is zero in both programs.

You might also like