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

Unit-4(oops)

Btech cse oops notes

Uploaded by

HIMANSHU SHARMA
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Unit-4(oops)

Btech cse oops notes

Uploaded by

HIMANSHU SHARMA
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Unit-4(Generic types and collections)

Generics: Generics is the idea to allow type (Integer, String, … etc and
user-defined types) to be a parameter to methods, classes and interfaces.
For example, classes like an array, map, etc, which can be used using
generics very efficiently. We can use them for any type.
The method of Generic Programming is implemented to increase the
efficiency of the code. Generic Programming enables the programmer to
write a general algorithm which will work with all data types. It eliminates
the need to create different algorithms if the data type is an integer, string
or a character.
The advantages of Generic Programming are
1. Code Reusability
2. Avoid Function Overloading
3. Once written it can be used for multiple times and cases.
4. Generics can be implemented in C++ using Templates. Template is
a simple and yet very powerful tool in C++. The simple idea is to
pass data type as a parameter so that we don’t need to write the
same code for different data types. For example, a software
company may need sort() for different data types. Rather than
writing and maintaining the multiple codes, we can write one sort()
and pass data type as a parameter.

5. Generic Functions using Template:

6. We write a generic function that can be used for different data types.
Examples of function templates are sort(), max(), min(), printArray()
#include <iostream>
using namespace std;

// One function works for all data types.


// This would work even for user defined types
// if operator '>' is overloaded
template <typename T>

T myMax(T x, T y)
{
return (x > y) ? x : y;
}

int main()
{

// Call myMax for int


cout << myMax<int>(3, 7) << endl;

// call myMax for double


cout << myMax<double>(3.0, 7.0) << endl;

// call myMax for char


cout << myMax<char>('g', 'e') << endl;

return 0;
}
Output:
7
7
g

Generic Class using Template:

Like function templates, class templates are useful when a class defines
something that is independent of data type. Can be useful for classes like
LinkedList, binary tree, Stack, Queue, Array, etc.
Following is a simple example of template Array class.
#include <iostream>
using namespace std;

template <typename T>


class Array {
private:
T* ptr;
int size;

public:
Array(T arr[], int s);
void print();
};

template <typename T>


Array<T>::Array(T arr[], int s)
{
ptr = new T[s];
size = s;
for (int i = 0; i < size; i++)
ptr[i] = arr[i];
}

template <typename T>


void Array<T>::print()
{
for (int i = 0; i < size; i++)
cout << " " << *(ptr + i);
cout << endl;
}

int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
Array<int> a(arr, 5);
a.print();
return 0;
}
Output:
1 2 3 4 5

subtype
subtyping is a key feature of object-oriented programming
languages such as Java. In Java, S is a subtype of T if S extends
or implements T.
Subtyping is transitive, meaning that if R is a subtype of S,
then R is also a subtype of T (T is the super type of
both Sand R).
Here are some examples:
- Integer is a subtype of Number
- ArrayList<E> is a subtype of Collection<E>
- String is a subtype of Object
The Collection classes from Java library is a good example of
this.

In the above diagram, The ArrayList<E> implements List<E> which in turn


extends Collection<E>. Similarly, the HashSet<E> implements Set<E> which
extends Collection<E>.

Wildcards
The question mark (?) is known as the wildcard in generic
programming. It represents an unknown type. The wildcard can
be used in a variety of situations such as the type of a
parameter, field, or local variable; sometimes as a return type.

Types of wildcards in Java

1. Upper Bounded Wildcards:


These wildcards can be used when you want to relax the
restrictions on a variable. For example, say you want to write a
method that works on List < Integer >, List < Double >, and List
< Number >, you can do this using an upper bounded wildcard.
To declare an upper-bounded wildcard, use the wildcard
character (‘?’), followed by the extends keyword, followed by its
upper bound.
public static void add(List<? extends Number> list)
// Java program to demonstrate Upper Bounded Wildcards
import java.util.Arrays;
import java.util.List;

class WildcardDemo {
public static void main(String[] args)
{

// Upper Bounded Integer List


List<Integer> list1 = Arrays.asList(4, 5, 6, 7);

// printing the sum of elements in list


System.out.println("Total sum is:" + sum(list1));

// Double list
List<Double> list2 = Arrays.asList(4.1, 5.1, 6.1);

// printing the sum of elements in list


System.out.print("Total sum is:" + sum(list2));
}

private static double sum(List<? extends Number> list)


{
double sum = 0.0;
for (Number i : list) {
sum += i.doubleValue();
}

return sum;
}
}
Output
Total sum is:22.0
Total sum is:15.299999999999999
Explanation:
In the above program, list1 and list2 are objects of the List class. list1 is a
collection of Integer and list2 is a collection of Double. Both of them are
being passed to method sum which has a wildcard that extends Number.
This means that list being passed can be of any field or subclass of that
field. Here, Integer and Double are subclasses of class Number.
2. Lower Bounded Wildcards :
It is expressed using the wildcard character (‘?’), followed by the super
keyword, followed by its lower bound: <? super A>.
Syntax: Collectiontype <? super A>
Implementation:
// Java program to demonstrate Lower Bounded Wildcards

import java.util.Arrays;
import java.util.List;

class WildcardDemo {
public static void main(String[] args)
{
// Lower Bounded Integer List
List<Integer> list1 = Arrays.asList(4, 5, 6, 7);

// Integer list object is being passed


printOnlyIntegerClassorSuperClass(list1);

// Number list
List<Number> list2 = Arrays.asList(4, 5, 6, 7);

// Integer list object is being passed


printOnlyIntegerClassorSuperClass(list2);
}

public static void printOnlyIntegerClassorSuperClass(


List<? super Integer> list)
{
System.out.println(list);
}
}
Output
[4, 5, 6, 7]
[4, 5, 6, 7]
Explanation:
Here arguments can be Integer or superclass of Integer(which
is Number). The method printOnlyIntegerClassorSuperClass
will only take Integer or its superclass objects. However, if we
pass a list of types Double then we will get a compilation error.
It is because only the Integer field or its superclass can be
passed. Double is not the superclass of Integer.
Note: Use extend wildcard when you want to get values out of
a structure and super wildcard when you put values in a
structure. Don’t use wildcard when you get and put values in a
structure. You can specify an upper bound for a wildcard, or
you can specify a lower bound, but you cannot specify both.
Unbounded Wildcard:
This wildcard type is specified using the wildcard character (?),
for example, List. This is called a list of unknown types. These
are useful in the following cases –
 When writing a method that can be employed using
functionality provided in Object class.
 When the code is using methods in the generic class that
doesn’t depend on the type parameter
Implementation:

// Java program to demonstrate Unbounded wildcard

import java.util.Arrays;

import java.util.List;

class unboundedwildcardemo {

public static void main(String[] args)

// Integer List

List<Integer> list1 = Arrays.asList(1, 2, 3);

// Double list

List<Double> list2 = Arrays.asList(1.1, 2.2, 3.3);

printlist(list1);
printlist(list2);

private static void printlist(List<?> list)

System.out.println(list);

}
}
Output
[1, 2, 3]
[1.1, 2.2, 3.3]

Set interface
The Set interface in Java is part of the Java Collections framework and provides the features of
a mathematical set. It extends the Collection interface and is used to create a collection that
does not allow duplicate elements12.
Key Principles

The Set interface is an unordered collection of objects in which duplicate values cannot be
stored. It contains methods inherited from the Collection interface and adds a feature that
restricts the insertion of duplicate elements1. The Set interface is implemented by several
classes, including HashSet, LinkedHashSet, EnumSet, and TreeSet2.
Common Methods

The Set interface includes all the methods of the Collection interface. Some commonly used
methods are:
 add(element): Adds the specified element to the set if it is not already present.
 addAll(collection): Adds all the elements of the specified collection to the set.
 clear(): Removes all the elements from the set.
 contains(element): Checks if the set contains the specified element.
 containsAll(collection): Checks if the set contains all the elements of the specified collection.
 iterator(): Returns an iterator to access elements of the set sequentially.
 remove(element): Removes the specified element from the set.
 removeAll(collection): Removes all the elements from the set that are present in another
specified set.
 retainAll(collection): Retains only the elements in the set that are also present in another
specified set.
 size(): Returns the number of elements in the set.
 toArray(): Returns an array containing all the elements of the set12.
Example Code

Here is an example of how to use the Set interface with the HashSet class:
import java.util.Set;
import java.util.HashSet;

public class SetExample {


public static void main(String[] args) {
// Creating a set using the HashSet class
Set<String> set = new HashSet<>();

// Adding elements to the set


set.add("Geeks");
set.add("For");
set.add("Geeks");
set.add("Example");
set.add("Set");

// Displaying the set


System.out.println("Set Elements: " + set);
}
}

Output:
Set Elements: [Set, Example, Geeks, For]

Set Operations

The Set interface allows performing basic mathematical set operations like union, intersection,
and difference:
 Union: Adds all elements from one set to another. Use addAll() method.
 Intersection: Retains only the common elements between two sets.
Use retainAll() method.
 Difference: Removes all elements from one set that are present in another set.
Use removeAll() method

Example:
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;

public class SetOperations {


public static void main(String[] args) {
Set<Integer> set1 = new HashSet<>(Arrays.asList(1, 3, 2, 4, 8, 9,
0));
Set<Integer> set2 = new HashSet<>(Arrays.asList(1, 3, 7, 5, 4, 0, 7,
5));

// Union
Set<Integer> union = new HashSet<>(set1);
union.addAll(set2);
System.out.println("Union: " + union);

// Intersection
Set<Integer> intersection = new HashSet<>(set1);
intersection.retainAll(set2);
System.out.println("Intersection: " + intersection);

// Difference
Set<Integer> difference = new HashSet<>(set1);
difference.removeAll(set2);
System.out.println("Difference: " + difference);
}
}

Output:
Union: [0, 1, 2, 3, 4, 5, 7, 8, 9]
Intersection: [0, 1, 3, 4]
Difference: [2, 8, 9]

Queue interface
The Queue Interface is present in java.util package and
extends the Collection interface is used to hold the elements
about to be processed in FIFO(First In First Out) order. It is an
ordered list of objects with its use limited to inserting elements
at the end of the list and deleting elements from the start of the
list, (i.e.), it follows the FIFO or the First-In-First-Out principle.

Being an interface the queue needs a concrete class for the


declaration and the most common classes are
the PriorityQueue and LinkedList in Java. Note that neither of
these implementations is thread-safe. PriorityBlockingQueue is
one alternative implementation if the thread-safe
implementation is needed.
Key Methods of the Queue Interface:

 offer(E e): Inserts the specified element into the queue if possible,
returning true upon success and false if no space is currently available.
 poll(): Retrieves and removes the head of the queue, or returns null if the
queue is empty.
 peek(): Retrieves, but does not remove, the head of the queue, or returns null if
the queue is empty.

Declaration: The Queue interface is declared as:

public interface Queue extends Collection

Deque Interface
Deque Interface present in java.util package is a subtype of
the queue interface. The Deque is related to the double-ended
queue that supports adding or removing elements from either
end of the data structure. It can either be used as a queue(first-
in-first-out/FIFO) or as a stack(last-in-first-out/LIFO) . Deque is the
acronym for double-ended queue.
The Deque (double-ended queue) interface in Java is a sub
interface of the Queue interface and extends it to provide a
double-ended queue, which is a queue that allows elements to
be added and removed from both ends. The Deque interface is
part of the Java Collections Framework and is used to provide a
generic and flexible data structure that can be used to
implement a variety of algorithms and data structures.
Here is an example of using a Deque in Java:

import java.util.ArrayDeque;

import java.util.Deque;

public class Example {

public static void main(String[] args) {

Deque<Integer> deque = new ArrayDeque<>();

deque.addFirst(1);
deque.addLast(2);

int first = deque.removeFirst();

int last = deque.removeLast();

System.out.println("First: " + first + ", Last: " + last);

}
}
Output
First: 1, Last: 2
Syntax: The deque interface is declared as,
public interface Deque extends Queue

Hierarchy Diagram of Queue and Deque Interface in Java

Map Interface
The map interface in Java is a structure that holds a set of key-value pairs where each
key is unique and points to one value only. It is a component of the java.util package and
is being widely used in Java programming to structure and get data in an ordered
manner. A Map is useful if you have to search, update or delete elements on the basis of
a key.

Why Java Map Interface?


Below are some circumstances and reasons where you may find it beneficial to utilize
the `Map` interface:

Efficient Data Retrieval: Keys are used in maps in order to read values selectively. If
you have to connect one set of data with another in a manner that enables you to find
the relevant information by typing the key, then the map answers your need very well.
For instance, in the case where you have a huge dataset and you want to quickly search
for anything that corresponds to specific keys, such as IDs, names, or codes, a map can
offer speedy access to such data.

No Duplicate Keys: Keys of maps are unique such that a particular key has to be
unique. This feature is handy when the goal is to make certain that each key should
represent only one value. Also, in a dictionary application, you would have to see that
each word has only one definition.
Flexibility in Key and Value Types: Java Maps feature the ability to store keys and
values of multiple types. You can use any object as a key, which must implement
hashCode() and equals() methods, and any object as a value. It provides you with the
chance to visualize different relationships between objects.

Associative Data Structures: Maps are frequently used for associative arrays,
dictionaries, and symbol tables. It offers convenient space for storing and retrieving
information, with each item having its own particular index.

Caching and Memoization: Maps are very useful for caching and memoization
purposes. You can save the results of a costly operation or a consequence of a certain
operation in a map, binding them with the inputs or the parameters of the operation. This
enables you to go straight to the stored map item if the same input occurs again, rather
than having to compute it again from scratch.
Useful methods of Map interface

Object Ordering
A List l may be sorted as follows.

Collections.sort(l);

If the List consists of String elements, it will be sorted into alphabetical order. If it consists
of Date elements, it will be sorted into chronological order. How does this
happen? String and Date both implement
the Comparable interface. Comparable implementations provide a natural ordering for a class, which
allows objects of that class to be sorted automatically. The following table summarizes some of the more
important Java platform classes that implement Comparable.
If you try to sort a list, the elements of which do not
implement Comparable, Collections.sort(list) will throw a ClassCastException.
Similarly, Collections.sort(list, comparator) will throw a ClassCastException if you try to
sort a list whose elements cannot be compared to one another using the comparator. Elements that can
be compared to one another are called mutually comparable. Although elements of different types may be
mutually comparable, none of the classes listed here permit interclass comparison.

SortedSet interface

The SortedSet interface extends Set and declares the behavior of a set
sorted in an ascending order. In addition to those methods defined by Set,
the SortedSet interface declares the methods summarized in the following
table −

Several methods throw a NoSuchElementException when no items are


contained in the invoking set. A ClassCastException is thrown when an object
is incompatible with the elements in a set.

A NullPointerException is thrown if an attempt is made to use a null object


and null is not allowed in the set.
SortedSet Interface Methods

Operations on SortedSet Interface


Creating a SortedSet
TreeSet class implements the SortedSet interface. We can use the TreeSet
constructor to create a SortedSet instance. Following is the syntax to create a
SortedSet instance:
Syntax
// Create the sorted set
SortedSet<String> set = new TreeSet<>();

Here we're creating a sorted set of String values. This map will store the
unique string values. If a duplicate value is added, then that will be
discarded.

Adding Value to a SortedSet


SortedSet provides an add() method, which can be used to add value to a
SortedSet instance. Whenever a value is added to the set, it is checked
against the existing values. If the set is modified then method will return true
otherwise false will be returned.
Syntax
public boolean add(E e)

Where E represents the element to be added. If element is already present,


then no action will be performed and method will return false.

Example
// Add elements to the set
set.add("b");
set.add("c");
set.add("a");
Getting value from a SortedSet
In order to get values from a SortedSet, we've to get the iterator object from
the SortedSet using the iterator() method. Once the iterator object is
available then that object can be used to retrieve values present in the
SortedSet.

Example
// Iterating over the elements in the set
Iterator it = set.iterator();
while (it.hasNext()) {
// Get element
Object element = it.next();
System.out.println(element.toString());
}
Deleting a value from a SortedSet
Using the remove(value) method, we can remove the value/object stored in
the SortedSet easily.
Syntax
public boolean remove(Object value)

if value is not present in the set, then it will return false otherwise it will
remove the value and return true.

set.remove("a");

SortedMap interface

The SortedMap interface extends Map. It ensures that the entries are
maintained in an ascending key order.
Several methods throw a NoSuchElementException when no items are in the
invoking map. A ClassCastException is thrown when an object is incompatible
with the elements in a map. A NullPointerException is thrown if an attempt is
made to use a null object when null is not allowed in the map.
SortedMap Interface Methods

The methods declared by SortedMap are summarized in the following table −


Operations on SortedMap Interface
Creating a SortedMap
TreeMap class implements the SortedMap interface. We can use the TreeMap constructor to
create a SortedMap instance.
Syntax

Following is the syntax to create a sortemap instance:

// Create a sorted map


SortedMap<String, Double> map = new TreeMap<>();

Here we're creating a sorted map of String vs Double values. This map will store the keys
based on alphanumeric order.

Adding Value to a SortedMap


SortedMap provides the put() method, which can be used to add value to a sortedmap
instance. Whenever a value is added to the map, the map automatically sorts itself based on
the keys entered.
Syntax
public V put(K key,V value)

Where the Key-Value pair represents the key and value associated with each other and are
stored in the map. If this key is already associated with a value then that value is returned and
the new value is associated with the key otherwise a null value is returned.
Example
// Put elements to the map
map.put("Zara", Double.valueOf(3434.34));
map.put("Mahnaz", Double.valueOf(123.22));
map.put("Ayan", Double.valueOf(1378.00));
map.put("Daisy", Double.valueOf(99.22));
map.put("Qadir", Double.valueOf(-19.08));
Getting value from a SortedMap
Using the get(key) method, we can retrieve the value associated with a key.
Syntax
public V get(Object key)

If the key is not present in the map, then it will return null otherwise it will return the
associated value with the key provided.

Example
Double value = map.get("Qadir");
System.out.print("Qadir: " + value);
Updating value of a SortedMap
We can update an existing value of a sortedmap by calling the put() method again with the
same key. Being a sortedmap, the entries will be sorted again based on the sorting order of
the newly entered key(s).
Example
// Put elements to the map
map.put("Zara", Double.valueOf(3434.34));
map.put("Mahnaz", Double.valueOf(123.22));
map.put("Zara", Double.valueOf(1378.00));
SortedMap will consider the latest put() method call to update the entry with same key.
Deleting a value from a sortedmap
Using remove(key) method, we can remove the key, value associated with a key.
Syntax
public V remove(Object key)

If key is not present in the map, then it will return null otherwise it will remove key-value
association from the map and sort the map accordingly.

Example
Double value = map.remove("Qadir");
System.out.print("Qadir removed with value: " + value);
Iterating sortedMap
SortedMap entries can be easily navigated. SortedMap provided a
method entrySet() which provides all the entries in form of set.
Syntax
public Set<Map.Entry<K,V>> entrySet()

Where Map.Entry contains the key-value pair to be iterated.

Example
// Get a set of the entries
Set<Map.Entry<String, Double>> set = map.entrySet();

// Get an iterator
Iterator<Map.Entry<String, Double>> i = set.iterator();

// Display elements
while(i.hasNext()) {
Map.Entry<String, Double> me = i.next();
System.out.println(me.getKey());
}

You might also like