0% found this document useful (0 votes)
19 views

20ES3102 Java Programming Unit IV Chapter 2 Collections Framework

Uploaded by

Hemanth chegondi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

20ES3102 Java Programming Unit IV Chapter 2 Collections Framework

Uploaded by

Hemanth chegondi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

20ES3102 – Java Programming

UNIT-IV
Chapter 2: Collections Framework
Collections Overview

Introduction:

A collection sometimes called a container is simply an object that groups multiple elements
into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate
data.

Collections in java are a framework that provides architecture to store and manipulate the
group of objects.

All the operations that you perform on a data such as searching, sorting, insertion,
manipulation, deletion etc. can be performed by Java Collections.

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

A data structure (Data Structure) can be termed as a storage box of data, or to say, a
collection of elements. To the storage, further elements can be added, existing elements can be
retrieved, deleted or replaced or can be copied to another Data Structure. In Java, a data structure
is a class (just like any other Java class) grouping multiple elements as a single entity (unit).
Contrary to arrays, a data structure grows dynamically when more elements are placed. Coming
to java, some data structures allow duplicate elements and some do not; some will accept null
values and some will print the elements automatically in ascending order.

Collection is a Java Interface. Collections can be used in various scenarios like Storing
phone numbers, Employee names database etc.

Collections Framework Java:

All the Data Structures that comes with JDK1.2 are put together called as collections
framework as the basic interface from which all the data structures are derived is Collection. The
collections framework comes with many interfaces like Collection, List, Set, Map and SortedMap
etc. From these interfaces many Data Structures are derived like LinkedList, TreeSet, ArrayList
and HashMap etc.

Mr.Raghu Virapratap
1
Asst. Professor
CSE Dept, V.R.S.E.C
All the collections framework classes are placed in java.util package. The java.util package
comes with many other service classes like Date, GregorianCalender and Random etc.

What is a framework?

A framework can be termed as a fundamental entity or structure developed to derive


solutions for many complicated problems. A framework includes interfaces, classes, support
programs, many resources and all converted into an API. A framework is reusable software
theoretically designed to work as a guide.

The designers started their collections framework with the introduction of basic interfaces
like Map, Collection, List and Set. Being interfaces, they give common functional methods for
many of their derived classes. The root interface of all is Collection. A point to note here is, a
collection also includes Map and SortedMap interfaces that are not derived from Collection. Map
and SortedMap have their own separate hierarchy; but still placed in Collections frame work.
Complete hierarchy is available at Java Collections Interfaces Hierarchy.

Collections Framework Java Grouping:

All the interfaces and their derived classes can be grouped into three core groups.

Interfaces: Three interfaces Collection, List and Map form the super classes for many concrete
classes. These interfaces give methods which subclasses implement so that all the subclasses have
common methods. It is easy to the programmer to remember. For example, to add an element for
any framework class is add() defined in Collection class.

Implementations: All the classes that implement the above three interfaces are known as
Collections Framework (in fact, these are data structures) and include LinkedList, TreeSet etc.

Algorithms: Algorithms make programmer life very easy. They are a bunch of static methods
with which DS elements can be manipulated. For example, obtaining maximum and minimum
values or sorting or filling all the elements with some values can be done in no time.

Collections framework Advantages:-

Following gives important advantages or features of collections framework classes.

Reduces programming effort with Software reusability: Designers took utmost care to
avoid unnecessary coding by the programmer for small simple operations like sorting, shuffling,
searching and knowing the frequency of an element occurring in a Data Structures. This avoids
redundancy and increases productivity. These methods can be used as it is by the the developer
without any modifications.

Mr.Raghu Virapratap
2
Asst. Professor
CSE Dept, V.R.S.E.C
Speed of execution and durability: Execution speed depends on the Data Structure you
choose depending on your coding needs. Some Data Structure methods are synchronized and
offers data consistency in multi threaded environments; but being synchronized reduces
performance. Choosing of Data Structure should consider the requirements like number of times
of Data Structure modification by adding new elements or retrieving is more than the addition,
data consistency required for critical important data etc.

Here comes node-based and array-based Data Structure (in node-based, addition will be
faster and in array-based, retrieval is faster). Programmer should be clever enough to choose a
correct DS for his needs taking into these numbers of factors into consideration.

Allows interoperability: One Data Structure elements can be passed to another Data
Structure within no time. Or one Data Structure can be assigned to another Data Structure, a Data
Structure can be cloned or a synchronized version of the existing Data Structures can be obtained
without disturbing the original Data Structure. This is possible because the super class of all Data
Strucure is Collection interface. It is one of the great design aspects designers followed. The node-
based DS elements can be converted into array-based Data Structure.

Reduces effort to practice new classes: As super class of all collections is Collection
interface, all the subclasses come with common methods with which a Data Structure can be
manipulated. Collections are a much matured framework and programmer need not depend on
other languages for any additional functionality.

Disadvantages:-

Care in casting: Casting in between the framework classes should be done with maximum
care like generics data types compatibility.

Runtime checks: Many DS throw runtime exceptions and programmer will be happy if
compile-time checks also exist.

Hierarchy of Collection Framework:

Let us see the hierarchy of collection framework. The java.util package contains all the
classes and interfaces for Collection framework.

Goals for Java Collections:

 The collections framework was designed to meet several goals.


 The framework had to be high-performance. The implementations for the
fundamental collections (dynamic arrays, linked lists, trees, and hash tables) are
highly efficient.
 The framework had to allow different types of collections to work in a similar
manner and with a high degree of interoperability.
 Extending and/or adapting a collection had to be easy.

Mr.Raghu Virapratap
3
Asst. Professor
CSE Dept, V.R.S.E.C
Collection represents the group of objects. Depending on the method of storing and
retrieving, collections are basically divided into three parts – Set, Map and List. Where Set does
not contain duplicate values, Map contains key value type of data whereas List can have a duplicate
values stored in it sequentially. This framework is provided in “java.util” package. Collection is
the parent interface of all collections in java.

Mr.Raghu Virapratap
4
Asst. Professor
CSE Dept, V.R.S.E.C
"Collection" the root of the collection hierarchy. A collection represents a group of objects known
as its elements. Some types of collections allow duplicate elements, and others do not. Some are
ordered and others are unordered. The Java platform doesn’t provide any direct implementations
of this interface but provides implementations of more specific sub interfaces, such as Set and List.

"Set" a collection that cannot contain duplicate elements

"List" an ordered collection (sometimes called a sequence). Lists can contain duplicate elements.
The user of a List generally has precise control over where in the list each element is inserted and
can access elements by their integer index (position).

"Queue" a collection used to hold multiple elements prior to processing. Besides basic Collection
operations, a Queue provides additional insertion, extraction, and inspection operations.

Queues typically, but do not necessarily, order elements in a FIFO (first-in, first-out)
manner. Among the exceptions are priority queues, which order elements according to a supplied
comparator or the elements natural ordering.
Mr.Raghu Virapratap
5
Asst. Professor
CSE Dept, V.R.S.E.C
"Map" an object that maps keys to values. A Map cannot contain duplicate keys; each key
can map to at most one value. If you’ve used Hashtable, you’re already familiar with the basics of
Map.

The Collection Interface

This enables you to work with groups of objects; it is at the top of the collections hierarchy.

Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No. Method Description


1 public boolean add(Object element) is used to insert an element in this collection.
2 public boolean addAll(Collection c) is used to insert the specified collection
elements in the invoking collection.
3 public boolean remove(Object element) is used to delete an element from this
collection.
4 public boolean removeAll(Collection c) is used to delete all the elements of specified
collection from the invoking collection.
5 public boolean retainAll(Collection c) is used to delete all the elements of invoking
collection except the specified collection.
6 public int size() return the total number of elements in the
collection.
7 public void clear() removes the total no of element from the
collection.
8 public boolean contains(Object is used to search an element.
element)
9 public boolean containsAll(Collection is used to search the specified collection in this
c) collection.
11 public Object[] toArray() converts collection into array.
12 public boolean isEmpty() checks if collection is empty.
13 public boolean equals(Object element) matches two collection.

The List Interface

Mr.Raghu Virapratap
6
Asst. Professor
CSE Dept, V.R.S.E.C
This extends Collection and an instance of List stores an ordered collection of elements.

The List interface extends Collection and declares the behavior of a collection that stores a
sequence of elements.

Elements can be inserted or accessed by their position in the list, using a zero-based index.

A list may contain duplicate elements. In addition to the methods defined by Collection, List
defines some of its own, which are summarized in the following table.

Several of the list methods will throw an UnsupportedOperationException if the collection


cannot be modified, and a ClassCastException is generated when one object is incompatible with
another.

Methods of Java List Interface

Method Description

void add(int index,Object element) It is used to insert element into the invoking list at
the index passed in the index.

boolean addAll(int index,Collection It is used to insert all elements of c into the invoking
c) list at the index passed in the index.

object get(int index) It is used to return the object stored at the specified
index within the invoking collection.

object set(int index,Object element) It is used to assign element to the location specified
by index within the invoking list.

object remove(int index) It is used to remove the element at position index


from the invoking list and return the deleted element.

Java - The Set Interface


A Set is a Collection that cannot contain duplicate elements. It models the mathematical set
abstraction.

The Set interface contains only methods inherited from Collection and adds the restriction that
duplicate elements are prohibited.

Set also adds a stronger contract on the behavior of the equals and hashCode operations,
allowing Set instances to be compared meaningfully even if their implementation types differ.
Mr.Raghu Virapratap
7
Asst. Professor
CSE Dept, V.R.S.E.C
List can contain duplicate elements whereas Set contains unique elements only.

Method Method & Description


add( ) Adds an object to the collection.

clear( ) Removes all objects from the collection.

contains( ) Returns true if a specified object is an element


within the collection.
isEmpty( ) Returns true if the collection has no elements.

remove( ) Removes a specified object from the collection.

Size() Returns the number of elements in the collection.

Java Map Interface

A map contains values on the basis of key i.e. key and value pair. Each key and value pair is known
as an entry. Map contains only unique keys.

Map is useful if you have to search, update or delete elements on the basis of key.

Useful methods of Map interface

Method Description

Object put(Object key, Object value) It is used to insert an entry in this map.

void putAll(Map map) It is used to insert the specified map in this map.

Object remove(Object key) It is used to delete an entry for the specified key.

Object get(Object key) It is used to return the value for the specified key.

boolean containsKey(Object key) It is used to search the specified key from this
map.

Set keySet() It is used to return the Set view containing all the
keys.

Mr.Raghu Virapratap
8
Asst. Professor
CSE Dept, V.R.S.E.C
Set entrySet() It is used to return the Set view containing all the
keys and values.

Java ArrayList class

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.

The important points about Java ArrayList class are:

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 array works at the index basis.
o In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred
if any element is removed from the array list.

Methods of Java ArrayList

Method Description

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

boolean addAll(Collection c) It is used to append 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.

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

int lastIndexOf(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.

boolean add(Object o) It is used to append the specified element to the end of a list.

boolean addAll(int index, It is used to insert all of the elements in the specified collection
Collection c) into this list, starting at the specified position.

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

Mr.Raghu Virapratap
9
Asst. Professor
CSE Dept, V.R.S.E.C
int indexOf(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.

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


the list's current size.

Java ArrayList Example

1. import java.util.*;
2. class TestCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }

Java LinkedList class

Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list
data structure.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
o Java LinkedList class can be used as list, stack or queue.

Mr.Raghu Virapratap
10
Asst. Professor
CSE Dept, V.R.S.E.C
Doubly Linked List

In case of doubly linked list, we can add or remove elements from both side.

Constructors of Java LinkedList

Constructor Description

LinkedList() It is used to construct an empty list.

Methods of Java LinkedList

Method Description

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

void addFirst(Object o) It is used to insert the given element at the beginning of a list.

void addLast(Object o) It is used to append the given element to the end of a list.

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

boolean add(Object o) It is used to append the specified element to the end of a list.

boolean contains(Object It is used to return true if the list contains a specified element.
o)

boolean remove(Object o) It is used to remove the first occurence of the specified element
in a list.

Object getFirst() It is used to return the first element in a list.

Object getLast() It is used to return the last element in a list.

int indexOf(Object o) It is used to return the index in a list of the first occurrence of
the specified element, or -1 if the list does not contain any
element.

Mr.Raghu Virapratap
11
Asst. Professor
CSE Dept, V.R.S.E.C
int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of
the specified element, or -1 if the list does not contain any
element.

Example of LinkedList

1. import java.util.*;
2. public class TestCollection
3. {
4. public static void main(String args[]){
5.
6. LinkedList<String> al=new LinkedList<String>();
7. al.add("Ravi");
8. al.add("Vijay");
9. al.add("Ravi");
10. al.add("Ajay");
11. Iterator<String> itr=al.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Java HashSet class

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.


o HashSet contains unique elements only.

Constructor Description

Mr.Raghu Virapratap
12
Asst. Professor
CSE Dept, V.R.S.E.C
HashSet() It is used to construct a default HashSet.

HashSet(Collection c) It is used to initialize the hash set by using the elements of the
collection c.

HashSet(int capacity) It is used to initialize the capacity of the hash set to the given integer
value capacity. The capacity grows automatically as elements are
added to the HashSet.

Method Description

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

boolean It is used to return true if this set contains the specified element.
contains(Object o)

boolean add(Object It is used to adds the specified element to this set if it is not already
o) present.

boolean isEmpty() It is used to return true if this set contains no elements.

boolean It is used to remove the specified element from this set if it is


remove(Object o) present.

Object clone() It is used to return a shallow copy of this HashSet instance: the
elements themselves are not cloned.

Iterator iterator() It is used to return an iterator over the elements in this set.

int size() It is used to return the number of elements in this set.

Java HashSet Example

1. import java.util.*;
2. class TestCollection9{

Mr.Raghu Virapratap
13
Asst. Professor
CSE Dept, V.R.S.E.C
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Java HashMap class

Java HashMap class implements the map interface by using a hashtable. It inherits AbstractMap
class and implements Map interface.

The important points about Java HashMap class are:

o A HashMap contains values based on the key.


o It contains only unique elements.
o It may have one null key and multiple null values.
o It maintains no order.

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable,


Serializable

HashMap class Parameters

Let's see the Parameters for java.util.HashMap class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Methods of Java HashMap class

Method Description
Mr.Raghu Virapratap
14
Asst. Professor
CSE Dept, V.R.S.E.C
void clear() It is used to remove all of the mappings from this map.

boolean containsKey(Object It is used to return true if this map contains a mapping for the
key) specified key.

boolean It is used to return true if this map maps one or more keys to
containsValue(Object value) the specified value.

boolean isEmpty() It is used to return true if this map contains no key-value


mappings.

Object clone() It is used to return a shallow copy of this HashMap instance:


the keys and values themselves are not cloned.

Set entrySet() It is used to return a collection view of the mappings contained


in this map.

Set keySet() It is used to return a set view of the keys contained in this map.

Object put(Object key, Object It is used to associate the specified value with the specified
value) key in this map.

int size() It is used to return the number of key-value mappings in this


map.

Collection values() It is used to return a collection view of the values contained in


this map.

Java HashMap Example

1. import java.util.*;
2. class TestCollection{
3. public static void main(String args[]){
4. HashMap<Integer,String> hm=new HashMap<Integer,String>();
5. hm.put(100,"Amit");
6. hm.put(101,"Vijay");
7. hm.put(102,"Rahul");
8. for(Map.Entry m:hm.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue());
10. }
11. }
12. }

Mr.Raghu Virapratap
15
Asst. Professor
CSE Dept, V.R.S.E.C
Java TreeMap class

Java TreeMap class implements the Map interface by using a tree. It provides an efficient means
of storing key/value pairs in sorted order.

The important points about Java TreeMap class are:

o A TreeMap contains values based on the key.


o It contains only unique elements.
o It cannot have null key but can have multiple null values.
o It is same as HashMap instead maintains ascending order.

TreeMap class declaration

Let's see the declaration for java.util.TreeMap class.

1. public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, C


loneable, Serializable

TreeMap class Parameters

Let's see the Parameters for java.util.TreeMap class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Method Description

boolean containsKey(Object It is used to return true if this map contains a mapping


key) for the specified key.

boolean containsValue(Object It is used to return true if this map maps one or more
value) keys to the specified value.

Object firstKey() It is used to return the first (lowest) key currently in


this sorted map.

Object get(Object key) It is used to return the value to which this map maps
the specified key.

Mr.Raghu Virapratap
16
Asst. Professor
CSE Dept, V.R.S.E.C
Object lastKey() It is used to return the last (highest) key currently in
this sorted map.

Object remove(Object key) It is used to remove the mapping for this key from this
TreeMap if present.

void putAll(Map map) It is used to copy all of the mappings from the specified
map to this map.

Set entrySet() It is used to return a set view of the mappings contained


in this map.

int size() It is used to return the number of key-value mappings


in this map.

Collection values() It is used to return a collection view of the values


contained in this map.

Java TreeMap Example:

1. import java.util.*;
2. class TestCollection15{
3. public static void main(String args[]){
4. TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
5. hm.put(100,"Amit");
6. hm.put(102,"Ravi");
7. hm.put(101,"Vijay");
8. hm.put(103,"Rahul");
9. for(Map.Entry m:hm.entrySet()){
10. System.out.println(m.getKey()+" "+m.getValue());
11. }
12. }
13. }

Mr.Raghu Virapratap
17
Asst. Professor
CSE Dept, V.R.S.E.C

You might also like