Unit-4(oops)
Unit-4(oops)
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.
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;
T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
return 0;
}
Output:
7
7
g
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;
public:
Array(T arr[], int s);
void print();
};
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.
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.
class WildcardDemo {
public static void main(String[] args)
{
// Double list
List<Double> list2 = Arrays.asList(4.1, 5.1, 6.1);
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);
// Number list
List<Number> list2 = Arrays.asList(4, 5, 6, 7);
import java.util.Arrays;
import java.util.List;
class unboundedwildcardemo {
// Integer List
// Double list
printlist(list1);
printlist(list2);
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;
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;
// 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.
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.
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;
deque.addFirst(1);
deque.addLast(2);
}
}
Output
First: 1, Last: 2
Syntax: The deque interface is declared as,
public interface Deque extends Queue
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.
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 −
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.
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
Here we're creating a sorted map of String vs Double values. This map will store the keys
based on alphanumeric order.
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()
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());
}