SlideShare a Scribd company logo
1 of 38
UNIT 3
Advanced Java
Content
• Collection frame work : Introduction, Benefits,
Collection Interfaces & Collection Implementation.
• Generic Programming : Introduction, Collection Frame
Work & Generic, Type Naming, Generic Methods &
Constructors, Type Inference, Bounded Type
Parameters, Wild cards, Type Erasure, Restrictions on
Generics.
Collection Framework
• 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).
Collection Framework
 What is Collection in Java ?
A Collection represents a single unit of objects, i.e., a group.
 What is a framework in Java ?
 It provides readymade architecture.
 It represents a set of classes and interfaces.
It is optional.
 What is Collection framework ?
The Collection framework represents a unified architecture for storing and manipulating a group of
objects. It has :-
 Interfaces and its implementations, i.e., classes
 Algorithm
Hierarchy of Collection Framework
The java.util package contains all the classes and interfaces for the Collection framework.
Implementation of Collection Framework
Before understanding the different components in the framework, let’s study a class and an interface.
• Class: A class is a user-defined blueprint or prototype from which objects are created. It represents
the set of properties or methods that are common to all objects of one type.
• Interface: An interface can have methods and variables, but the methods declared in an interface
are by default abstract. Interfaces specify what a class must do and not how.
 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.
 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, void clear(), etc. which are implemented by all the subclasses of Collection
interface.
Implementation of Collection Framework
 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. 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 :-
 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.
 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.
 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.
Implementation of Collection Framework
 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.
 Queue Interface – Queue interface maintains the first-in-first-out order. It can be defined as an
ordered list that is used to hold the elements which are about to be processed. There are various
classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
 PriorityQueue – The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null values to be
stored in the queue.
 Deque Interface – Deque interface extends the Queue interface. In Deque, we can remove and add
the elements from both the side. Deque stands for a double-ended queue which enables us to
perform the operations at both the ends.
 ArrayDeque – ArrayDeque class implements the Deque interface. It facilitates us to use the Deque.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Implementation of Collection Framework
 Set Interface – Set Interface in Java is present in java.util package. It extends the Collection
interface. It represents the unordered set of elements which doesn't allow us to store the duplicate
items. We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet,
and TreeSet.
 HashSet – HashSet class implements Set Interface. It represents the collection that uses a hash
table for storage. Hashing is used to store the elements in the HashSet. It contains unique items.
 LinkedHashSet - LinkedHashSet class represents the LinkedList implementation of Set Interface. It
extends the HashSet class and implements Set interface. Like HashSet, It also contains unique
elements. It maintains the insertion order and permits null elements.
 SortedSet Interface – SortedSet is the alternate of Set interface that provides a total ordering on its
elements. The elements of the SortedSet are arranged in the increasing order. The SortedSet
provides the additional methods that inhibit the natural ordering of the elements.
 TreeSet – Java TreeSet class implements the Set interface that uses a tree for storage. However, the
access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
Program – ArrayList & LinkedList
 ArrayList :-
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("Ravi");
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :-
Ravi
Vijay
Ravi
Ajay
 LinkedList :-
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :-
Ravi
Vijay
Ravi
Ajay
Program – Vector & Stack
 Vector :-
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :-
Ayush
Amit
Ashish
Garima
 Stack :-
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :-
Ayush
Garvit
Amit
Ashish
Program – PriorityQueue
 Priority Queue :-
import java.util.*;
public class TestJavaCollection5{
public static void main(String args[]){
PriorityQueue<String> queue=new
PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output :-
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
Program – ArrayDeque & HashSet
 ArrayDeque :-
import java.util.*;
public class TestJavaCollection6{
public static void main(String[] args) {
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
for (String str : deque) {
System.out.println(str);
}
}
}
Output :-
Gautam
Karan
Ajay
 HashSet :-
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :-
Vijay
Ravi
Ajay
Program – LinkedHashSet & TreeSet
 LinkedHashSet :-
import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new
LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :-
Ravi
Vijay
Ajay
 TreeSet :-
import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :-
Ajay
Ravi
Vijay
Benefits of Collection Framework
 Advantages of the Collection Framework :-
1. Consistent API :- The API has a basic set of interfaces like Collection, Set, List, or Map, all the
classes that implement these interfaces have some common set of methods.
2. Reduces programming effort :- A programmer doesn’t have to worry about the design of the
Collection but rather he can focus on its best use in his program. Therefore, the basic concept of
Object-oriented programming i.e. abstraction has been successfully implemented.
3. Increases program speed and quality :- Increases performance by providing high-performance
implementations of useful data structures and algorithms because in this case, the programmer
need not think of the best implementation of a specific data structure. He can simply use the best
implementation to drastically boost the performance of his algorithm.
Generics
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-
defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to
create classes that work with different data types. An entity such as class, interface, or method that
operates on a parameterized type is a generic entity.
For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well.
 Type Parameters :- The type parameters naming conventions are important to learn generics
thoroughly. The common type parameters are as follows :-
1. T – Type
2. E – Element
3. K – Key
4. N – Number
5. V – Value
Generic Method
 Generic Method – Generic Java method takes a parameter and returns some value after performing
a task. It is exactly like a normal function, however, a generic method has type parameters that are
cited by actual type. This allows the generic method to be used in a more general way. The compiler
takes care of the type of safety which enables programmers to code easily since they do not have to
perform long, individual type castings.
 Generic Classes – A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of
parameter, separated by a comma. The classes, which accept one or more parameters, ​are known
as parameterized classes or parameterized types.
 Generic Functions – We can also write generic functions that can be called with different types of
arguments based on the type of arguments passed to the generic method. The compiler handles
each method.
 Generics Work Only with Reference Types – When we declare an instance of a generic type, the
type argument passed to the type parameter must be a reference type. We cannot use primitive
data types like int, char.
Generic Constructors & Interfaces
 Generic constructors – They are same as generic methods. For generic constructors after the public
keyword and before the class name the type parameter must be placed. Constructors can be
invoked with any type of a parameter after defining a generic constructor. A constructor is a block
of code that initializes the newly created object. It is an instance method with no return type. The
name of the constructor is same as the class name. Constructors can be Generic, despite its class is
not Generic.
 Generic Interfaces – They are the interfaces in Java that deal with abstract data types. Interface
help in the independent manipulation of java collections from representation details. They are used
to achieving multiple inheritance in java forming hierarchies. They differ from the java class. These
include all abstract methods only, have static and final variables only. The only reference can be
created to interface, not objects. This involves the “implements” keyword. These are similar to
generic classes.
Program for Generics in Java
import java.util.*;
class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
list.add("rahul");
list.add("jai");
//list.add(32);
String s=list.get(1);
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output :-
element is: jai
rahul
jai
Program – Type Parameter Naming Conventions
package com.tutorialspoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GenericsTester {
public static void main(String[] args) {
Box<Integer, String> box = new Box<Integer,
String>();
box.add(Integer.valueOf(10),"Hello World");
System.out.printf("Integer Value :%dn",
box.getFirst());
System.out.printf("String Value :%sn",
box.getSecond());
Pair<String, Integer> pair = new Pair<String,
Integer>();
pair.addKeyValue("1", Integer.valueOf(10));
System.out.printf("(Pair)Integer Value :%dn",
pair.getValue("1"));
CustomList<Box> list = new CustomList<Box>();
list.addItem(box);
System.out.printf("(CustomList)Integer Value :%dn",
list.getItem(0).getFirst());
}
}
class Box<T, S> {
private T t;
private S s;
public void add(T t, S s) {
this.t = t;
this.s = s;
}
public T getFirst() {
return t;
}
public S getSecond() {
return s;
}
}
class Pair<K,V>{
Program – Type Parameter Naming Conventions
private Map<K,V> map = new HashMap<K,V>();
public void addKeyValue(K key, V value) {
map.put(key, value);
}
public V getValue(K key) {
return map.get(key);
}
}
class CustomList<E>{
private List<E> list = new ArrayList<E>();
public void addItem(E value) {
list.add(value);
}
public E getItem(int index) {
return list.get(index);
}
}
Output :-
Integer Value :10
String Value :Hello World
(Pair)Integer Value :10
(CustomList)Integer Value :10
Program to implement Java Method
public class TestGenerics4{
public static < E > void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
System.out.println();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'J', 'A', 'V', 'A' };
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}
Output :-
Printing Integer Array
10
20
30
40
50
Printing Character Array
J
A
V
A
Program to implement Java Constructors
// Java Program to illustrate Generic constructors
// Importing input output classes
import java.io.*;
// Class 1
// Generic class
class GenericConstructor {
private double v;
<T extends Number> GenericConstructor(T t)
{
v = t.doubleValue();
}
void show()
{
System.out.println("v: " + v);
}
}
class GFG {
public static void main(String[] args)
{
System.out.println("Number to
Double Conversion:");
GenericConstructor obj1
= new
GenericConstructor(10);
GenericConstructor obj2
= new
GenericConstructor(136.8F);
obj1.show();
obj2.show();
}
}
Output :-
Number to Double Conversion:
v: 10.0
v: 136.8000030517578
Advantages of Generics
1. Code Reuse – We can write a method/class/interface once and use it for any type we want.
2. Type Safety – Generics make errors to appear compile time than at run time (It’s always better to
know problems in your code at compile time rather than making your code fail at run time).
Suppose you want to create an ArrayList that store name of students, and if by mistake the
programmer adds an integer object instead of a string, the compiler allows it. But, when we
retrieve this data from ArrayList, it causes problems at runtime.
3. Individual Type Casting is not needed – If we do not use generics, then, in the above example,
every time we retrieve data from ArrayList, we have to typecast it. Typecasting at every retrieval
operation is a big headache. If we already know that our list only holds string data, we need not
typecast it every time.
4. Generics Promotes Code Reusability – With the help of generics in Java, we can write code that
will work with different types of data.
5. Implementing Generic Algorithms – By using generics, we can implement algorithms that work on
different types of objects, and at the same, they are type-safe too.
Type Inference in Java
Type inference represents the Java compiler's ability to look at a method invocation and its
corresponding declaration to check and determine the type argument(s). The inference algorithm
checks the types of the arguments and, if available, assigned type is returned. Inference algorithms
tries to find a specific type which can fullfill all type parameters.
Compiler generates unchecked conversion warning in-case type inference is not used.
 Syntax :- Box<Integer> integerBox = new Box<>();
where,
Box − Box is a generic class.
<> − The diamond operator denotes type inference.
Program – Type Inference
package com.tutorialspoint;
public class GenericsTester {
public static void main(String[] args) {
//type inference
Box<Integer> integerBox = new Box<>();
Box<String> stringBox = new Box<String>();
integerBox.add(new Integer(10));
stringBox.add(new String("Hello World"));
System.out.printf("Integer Value :%dn",
integerBox.get());
System.out.printf("String Value :%sn",
stringBox.get());
}
}
class Box<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
Output :-
Integer Value :10
String Value :Hello World
Bounded Type Parameter
There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a
type parameter. For example, a method that operates on numbers might only want to accept instances
of Number or its subclasses. This is what bounded type parameters are for.
How to Declare a Bounded Type Parameter in Java?
1. List the type parameter’s name,
2. Along with the extends keyword
3. And by its upper bound. (which in the below example c is A.)
 Syntax :- <T extends superClassName>
 Multiple Bounds :- Bounded type parameters can be used with methods as well as classes and
interfaces.
Java Generics supports multiple bounds also, i.e., In this case, A can be an interface or class. If A is
class, then B and C should be interfaces. We can’t have more than one class in multiple bounds.
 Syntax :- <T extends superClassName & Interface>
Program – Bounded Type Parameter
public class MaximumTest {
// determines the largest of three Comparable objects
public static <T extends Comparable<T>> T
maximum(T x, T y, T z) {
T max = x;
if(y.compareTo(max) > 0) {
max = y;
}
if(z.compareTo(max) > 0) {
max = z;
}
return max;
}
public static void main(String args[]) {
System.out.printf("Max of %d, %d and %d is
%dnn",
3, 4, 5, maximum( 3, 4, 5 ));
System.out.printf("Max of %.1f,%.1f and %.1f is
%.1fnn",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));
System.out.printf("Max of %s, %s and %s is
%sn","pear",
"apple", "orange", maximum("pear", "apple",
"orange"));
}
}
Output :-
Max of 3, 4 and 5 is 5
Max of 6.6,8.8 and 7.7 is 8.8
Max of pear, apple and orange is pear
Wild Card in Java
The ? (question mark) symbol represents the wildcard element. It means any type. If we write <?
extends Number>, it means any child class of Number, e.g., Integer, Float, and double. Now we can call
the method of Number class through any child class object.
We can use a wildcard as a type of a parameter, field, return type, or local variable. However, it is not
allowed to use a wildcard as a type argument for a generic method invocation, a generic class instance
creation, or a supertype.
They are of three types :-
1. Upper Bounded Wildcard
2. Unbounded Wildcard
3. Lower Bounded Wildcard
Program for Wildcard in Java Generic
import java.util.*;
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle");}
}
class GenericTest{
public static void drawShapes(List<? extends Shape>
lists){
for(Shape s:lists){
s.draw();
instance
}
}
public static void main(String args[]){
List<Rectangle> list1=new ArrayList<Rectangle>();
list1.add(new Rectangle());
List<Circle> list2=new ArrayList<Circle>();
list2.add(new Circle());
list2.add(new Circle());
drawShapes(list1);
drawShapes(list2);
}}
Output :-
drawing rectangle
drawing circle
drawing circle
Types of Wildcard
1. Upper Bounded Wildcards :- The purpose of upper bounded wildcards is to decrease the restrictions
on a variable. It restricts the unknown type to be a specific type or a subtype of that type. It is used by
declaring wildcard character ("?") followed by the extends or implements keyword, followed by its
upper bound.
Syntax :- List<? extends Number>
Here, extends, is a keyword. Number, is a class present in java.lang package
2. Lower Bounded Wildcards :- The purpose of lower bounded wildcards is to restrict the unknown
type to be a specific type or a supertype of that type. It is used by declaring wildcard character ("?")
followed by the super keyword, followed by its lower bound.
Syntax :- List<? super Integer>
Here, super, is a keyword. Integer, is a wrapper class.
3. Unbounded Wildcards :- This type represents the list of an unknown type such as List<?>.
This approach can be useful in the following scenarios: -
• When the given method is implemented by using the functionality provided in the Object class.
• When the generic class contains the methods that don't depend on the type parameter.
Program for Upper Bounded Wildcard
// Java program to demonstrate Upper Bounded
Wildcards
import java.util.Arrays;
import java.util.List;
class WildcardDemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList(4,
5, 6, 7);
System.out.println("Total sum is:" +
sum(list1));
List<Double> list2 =
Arrays.asList(4.1, 5.1, 6.1);
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
Program for Lower Bounded Wildcard
// Java program to demonstrate Lower Bounded
Wildcards
import java.util.Arrays;
import java.util.List;
class WildcardDemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList(4,
5, 6, 7);
printOnlyIntegerClassorSuperClass(list1);
List<Number> list2 =
Arrays.asList(4, 5, 6, 7);
printOnlyIntegerClassorSuperClass(list2);
}
public static void
printOnlyIntegerClassorSuperClass(
List<? super Integer> list)
{
System.out.println(list);
}
}
Output :-
[4, 5, 6, 7]
[4, 5, 6, 7]
Program for Unbounded Wildcard
// Java program to demonstrate Unbounded wildcard
import java.util.Arrays;
import java.util.List;
class unboundedwildcardemo {
public static void main(String[] args)
{
List<Integer> list1 = Arrays.asList(1,
2, 3);
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]
Type Erasure
Generics are used for tighter type checks at compile time and to provide a generic programming. To
implement generic behaviour, java compiler apply type erasure. Type erasure is a process in which
compiler replaces a generic parameter with actual class or bridge method. In type erasure, compiler
ensures that no extra classes are created and there is no runtime overhead.
 Type Erasure rules :-
 Replace type parameters in generic type with their bound if bounded type parameters are used.
 Replace type parameters in generic type with Object if unbounded type parameters are used.
 Insert type casts to preserve type safety.
 Generate bridge methods to keep polymorphism in extended generic types.
Restrictions on Generics
To use Java generics effectively, you must consider the following restrictions :-
 Cannot Instantiate Generic Types with Primitive Types
 Cannot Create Instances of Type Parameters
 Cannot Declare Static Fields Whose Types are Type Parameters
 Cannot Use Casts or instanceof With Parameterized Types
 Cannot Create Arrays of Parameterized Types
 Cannot Create, Catch, or Throw Objects of Parameterized Types
 Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same
Raw Type
THANK YOU

More Related Content

Similar to Advanced Java - UNIT 3.pptx

Java collections
Java collectionsJava collections
Java collections
padmad2291
 
Week_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdfWeek_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdf
PrabhaK22
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Java collections
Java collectionsJava collections
Java collections
Amar Kutwal
 
Discuss the characteristics of ArrayList, LinkedList, and Vector and.pdf
Discuss the characteristics of ArrayList, LinkedList, and Vector and.pdfDiscuss the characteristics of ArrayList, LinkedList, and Vector and.pdf
Discuss the characteristics of ArrayList, LinkedList, and Vector and.pdf
info785431
 
Java collections-interview-questions
Java collections-interview-questionsJava collections-interview-questions
Java collections-interview-questions
yearninginjava
 

Similar to Advanced Java - UNIT 3.pptx (20)

Collection framework
Collection frameworkCollection framework
Collection framework
 
Java collections
Java collectionsJava collections
Java collections
 
JAVA(UNIT 4)
JAVA(UNIT 4)JAVA(UNIT 4)
JAVA(UNIT 4)
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Lecture 24
Lecture 24Lecture 24
Lecture 24
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java collections
Java collectionsJava collections
Java collections
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Week_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdfWeek_2_Lec_6-10_with_watermarking_(1).pdf
Week_2_Lec_6-10_with_watermarking_(1).pdf
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Java collections
Java collectionsJava collections
Java collections
 
Java collections
Java collectionsJava collections
Java collections
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
Discuss the characteristics of ArrayList, LinkedList, and Vector and.pdf
Discuss the characteristics of ArrayList, LinkedList, and Vector and.pdfDiscuss the characteristics of ArrayList, LinkedList, and Vector and.pdf
Discuss the characteristics of ArrayList, LinkedList, and Vector and.pdf
 
Java collections-interview-questions
Java collections-interview-questionsJava collections-interview-questions
Java collections-interview-questions
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Java Collection Interview Questions [Updated]
Java Collection Interview Questions [Updated]Java Collection Interview Questions [Updated]
Java Collection Interview Questions [Updated]
 
Java.util
Java.utilJava.util
Java.util
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
 

Recently uploaded

QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
httgc7rh9c
 

Recently uploaded (20)

UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lessonQUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
QUATER-1-PE-HEALTH-LC2- this is just a sample of unpacked lesson
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 

Advanced Java - UNIT 3.pptx

  • 1.
  • 3. Content • Collection frame work : Introduction, Benefits, Collection Interfaces & Collection Implementation. • Generic Programming : Introduction, Collection Frame Work & Generic, Type Naming, Generic Methods & Constructors, Type Inference, Bounded Type Parameters, Wild cards, Type Erasure, Restrictions on Generics.
  • 4. Collection Framework • 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).
  • 5. Collection Framework  What is Collection in Java ? A Collection represents a single unit of objects, i.e., a group.  What is a framework in Java ?  It provides readymade architecture.  It represents a set of classes and interfaces. It is optional.  What is Collection framework ? The Collection framework represents a unified architecture for storing and manipulating a group of objects. It has :-  Interfaces and its implementations, i.e., classes  Algorithm
  • 6. Hierarchy of Collection Framework The java.util package contains all the classes and interfaces for the Collection framework.
  • 7. Implementation of Collection Framework Before understanding the different components in the framework, let’s study a class and an interface. • Class: A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. • Interface: An interface can have methods and variables, but the methods declared in an interface are by default abstract. Interfaces specify what a class must do and not how.  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.  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, void clear(), etc. which are implemented by all the subclasses of Collection interface.
  • 8. Implementation of Collection Framework  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. 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 :-  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.  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.  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.
  • 9. Implementation of Collection Framework  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.  Queue Interface – Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold the elements which are about to be processed. There are various classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.  PriorityQueue – The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be processed by their priorities. PriorityQueue doesn't allow null values to be stored in the queue.  Deque Interface – Deque interface extends the Queue interface. In Deque, we can remove and add the elements from both the side. Deque stands for a double-ended queue which enables us to perform the operations at both the ends.  ArrayDeque – ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
  • 10. Implementation of Collection Framework  Set Interface – Set Interface in Java is present in java.util package. It extends the Collection interface. It represents the unordered set of elements which doesn't allow us to store the duplicate items. We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet, and TreeSet.  HashSet – HashSet class implements Set Interface. It represents the collection that uses a hash table for storage. Hashing is used to store the elements in the HashSet. It contains unique items.  LinkedHashSet - LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the HashSet class and implements Set interface. Like HashSet, It also contains unique elements. It maintains the insertion order and permits null elements.  SortedSet Interface – SortedSet is the alternate of Set interface that provides a total ordering on its elements. The elements of the SortedSet are arranged in the increasing order. The SortedSet provides the additional methods that inhibit the natural ordering of the elements.  TreeSet – Java TreeSet class implements the Set interface that uses a tree for storage. However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
  • 11. Program – ArrayList & LinkedList  ArrayList :- import java.util.*; class TestJavaCollection1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>(); list.add("Ravi"); list.add("Vijay"); list.add("Ravi"); list.add("Ajay"); Iterator itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output :- Ravi Vijay Ravi Ajay  LinkedList :- import java.util.*; public class TestJavaCollection2{ public static void main(String args[]){ LinkedList<String> al=new LinkedList<String>(); al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay"); Iterator<String> itr=al.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output :- Ravi Vijay Ravi Ajay
  • 12. Program – Vector & Stack  Vector :- import java.util.*; public class TestJavaCollection3{ public static void main(String args[]){ Vector<String> v=new Vector<String>(); v.add("Ayush"); v.add("Amit"); v.add("Ashish"); v.add("Garima"); Iterator<String> itr=v.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output :- Ayush Amit Ashish Garima  Stack :- import java.util.*; public class TestJavaCollection4{ public static void main(String args[]){ Stack<String> stack = new Stack<String>(); stack.push("Ayush"); stack.push("Garvit"); stack.push("Amit"); stack.push("Ashish"); stack.push("Garima"); stack.pop(); Iterator<String> itr=stack.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output :- Ayush Garvit Amit Ashish
  • 13. Program – PriorityQueue  Priority Queue :- import java.util.*; public class TestJavaCollection5{ public static void main(String args[]){ PriorityQueue<String> queue=new PriorityQueue<String>(); queue.add("Amit Sharma"); queue.add("Vijay Raj"); queue.add("JaiShankar"); queue.add("Raj"); System.out.println("head:"+queue.element()); System.out.println("head:"+queue.peek()); System.out.println("iterating the queue elements:"); Iterator itr=queue.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } queue.remove(); queue.poll(); System.out.println("after removing two elements:"); Iterator<String> itr2=queue.iterator(); while(itr2.hasNext()){ System.out.println(itr2.next()); } } } Output :- head:Amit Sharma head:Amit Sharma iterating the queue elements: Amit Sharma Raj JaiShankar Vijay Raj after removing two elements: Raj Vijay Raj
  • 14. Program – ArrayDeque & HashSet  ArrayDeque :- import java.util.*; public class TestJavaCollection6{ public static void main(String[] args) { Deque<String> deque = new ArrayDeque<String>(); deque.add("Gautam"); deque.add("Karan"); deque.add("Ajay"); for (String str : deque) { System.out.println(str); } } } Output :- Gautam Karan Ajay  HashSet :- import java.util.*; public class TestJavaCollection7{ public static void main(String args[]){ HashSet<String> set=new HashSet<String>(); set.add("Ravi"); set.add("Vijay"); set.add("Ravi"); set.add("Ajay"); Iterator<String> itr=set.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output :- Vijay Ravi Ajay
  • 15. Program – LinkedHashSet & TreeSet  LinkedHashSet :- import java.util.*; public class TestJavaCollection8{ public static void main(String args[]){ LinkedHashSet<String> set=new LinkedHashSet<String>(); set.add("Ravi"); set.add("Vijay"); set.add("Ravi"); set.add("Ajay"); Iterator<String> itr=set.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output :- Ravi Vijay Ajay  TreeSet :- import java.util.*; public class TestJavaCollection9{ public static void main(String args[]){ TreeSet<String> set=new TreeSet<String>(); set.add("Ravi"); set.add("Vijay"); set.add("Ravi"); set.add("Ajay"); Iterator<String> itr=set.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output :- Ajay Ravi Vijay
  • 16. Benefits of Collection Framework  Advantages of the Collection Framework :- 1. Consistent API :- The API has a basic set of interfaces like Collection, Set, List, or Map, all the classes that implement these interfaces have some common set of methods. 2. Reduces programming effort :- A programmer doesn’t have to worry about the design of the Collection but rather he can focus on its best use in his program. Therefore, the basic concept of Object-oriented programming i.e. abstraction has been successfully implemented. 3. Increases program speed and quality :- Increases performance by providing high-performance implementations of useful data structures and algorithms because in this case, the programmer need not think of the best implementation of a specific data structure. He can simply use the best implementation to drastically boost the performance of his algorithm.
  • 17. Generics Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user- defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types. An entity such as class, interface, or method that operates on a parameterized type is a generic entity. For example, classes like HashSet, ArrayList, HashMap, etc., use generics very well.  Type Parameters :- The type parameters naming conventions are important to learn generics thoroughly. The common type parameters are as follows :- 1. T – Type 2. E – Element 3. K – Key 4. N – Number 5. V – Value
  • 18. Generic Method  Generic Method – Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the generic method to be used in a more general way. The compiler takes care of the type of safety which enables programmers to code easily since they do not have to perform long, individual type castings.  Generic Classes – A generic class is implemented exactly like a non-generic class. The only difference is that it contains a type parameter section. There can be more than one type of parameter, separated by a comma. The classes, which accept one or more parameters, ​are known as parameterized classes or parameterized types.  Generic Functions – We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to the generic method. The compiler handles each method.  Generics Work Only with Reference Types – When we declare an instance of a generic type, the type argument passed to the type parameter must be a reference type. We cannot use primitive data types like int, char.
  • 19. Generic Constructors & Interfaces  Generic constructors – They are same as generic methods. For generic constructors after the public keyword and before the class name the type parameter must be placed. Constructors can be invoked with any type of a parameter after defining a generic constructor. A constructor is a block of code that initializes the newly created object. It is an instance method with no return type. The name of the constructor is same as the class name. Constructors can be Generic, despite its class is not Generic.  Generic Interfaces – They are the interfaces in Java that deal with abstract data types. Interface help in the independent manipulation of java collections from representation details. They are used to achieving multiple inheritance in java forming hierarchies. They differ from the java class. These include all abstract methods only, have static and final variables only. The only reference can be created to interface, not objects. This involves the “implements” keyword. These are similar to generic classes.
  • 20. Program for Generics in Java import java.util.*; class TestGenerics1{ public static void main(String args[]){ ArrayList<String> list=new ArrayList<String>(); list.add("rahul"); list.add("jai"); //list.add(32); String s=list.get(1); System.out.println("element is: "+s); Iterator<String> itr=list.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } } } Output :- element is: jai rahul jai
  • 21. Program – Type Parameter Naming Conventions package com.tutorialspoint; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GenericsTester { public static void main(String[] args) { Box<Integer, String> box = new Box<Integer, String>(); box.add(Integer.valueOf(10),"Hello World"); System.out.printf("Integer Value :%dn", box.getFirst()); System.out.printf("String Value :%sn", box.getSecond()); Pair<String, Integer> pair = new Pair<String, Integer>(); pair.addKeyValue("1", Integer.valueOf(10)); System.out.printf("(Pair)Integer Value :%dn", pair.getValue("1")); CustomList<Box> list = new CustomList<Box>(); list.addItem(box); System.out.printf("(CustomList)Integer Value :%dn", list.getItem(0).getFirst()); } } class Box<T, S> { private T t; private S s; public void add(T t, S s) { this.t = t; this.s = s; } public T getFirst() { return t; } public S getSecond() { return s; } } class Pair<K,V>{
  • 22. Program – Type Parameter Naming Conventions private Map<K,V> map = new HashMap<K,V>(); public void addKeyValue(K key, V value) { map.put(key, value); } public V getValue(K key) { return map.get(key); } } class CustomList<E>{ private List<E> list = new ArrayList<E>(); public void addItem(E value) { list.add(value); } public E getItem(int index) { return list.get(index); } } Output :- Integer Value :10 String Value :Hello World (Pair)Integer Value :10 (CustomList)Integer Value :10
  • 23. Program to implement Java Method public class TestGenerics4{ public static < E > void printArray(E[] elements) { for ( E element : elements){ System.out.println(element ); } System.out.println(); } public static void main( String args[] ) { Integer[] intArray = { 10, 20, 30, 40, 50 }; Character[] charArray = { 'J', 'A', 'V', 'A' }; System.out.println( "Printing Integer Array" ); printArray( intArray ); System.out.println( "Printing Character Array" ); printArray( charArray ); } } Output :- Printing Integer Array 10 20 30 40 50 Printing Character Array J A V A
  • 24. Program to implement Java Constructors // Java Program to illustrate Generic constructors // Importing input output classes import java.io.*; // Class 1 // Generic class class GenericConstructor { private double v; <T extends Number> GenericConstructor(T t) { v = t.doubleValue(); } void show() { System.out.println("v: " + v); } } class GFG { public static void main(String[] args) { System.out.println("Number to Double Conversion:"); GenericConstructor obj1 = new GenericConstructor(10); GenericConstructor obj2 = new GenericConstructor(136.8F); obj1.show(); obj2.show(); } } Output :- Number to Double Conversion: v: 10.0 v: 136.8000030517578
  • 25. Advantages of Generics 1. Code Reuse – We can write a method/class/interface once and use it for any type we want. 2. Type Safety – Generics make errors to appear compile time than at run time (It’s always better to know problems in your code at compile time rather than making your code fail at run time). Suppose you want to create an ArrayList that store name of students, and if by mistake the programmer adds an integer object instead of a string, the compiler allows it. But, when we retrieve this data from ArrayList, it causes problems at runtime. 3. Individual Type Casting is not needed – If we do not use generics, then, in the above example, every time we retrieve data from ArrayList, we have to typecast it. Typecasting at every retrieval operation is a big headache. If we already know that our list only holds string data, we need not typecast it every time. 4. Generics Promotes Code Reusability – With the help of generics in Java, we can write code that will work with different types of data. 5. Implementing Generic Algorithms – By using generics, we can implement algorithms that work on different types of objects, and at the same, they are type-safe too.
  • 26. Type Inference in Java Type inference represents the Java compiler's ability to look at a method invocation and its corresponding declaration to check and determine the type argument(s). The inference algorithm checks the types of the arguments and, if available, assigned type is returned. Inference algorithms tries to find a specific type which can fullfill all type parameters. Compiler generates unchecked conversion warning in-case type inference is not used.  Syntax :- Box<Integer> integerBox = new Box<>(); where, Box − Box is a generic class. <> − The diamond operator denotes type inference.
  • 27. Program – Type Inference package com.tutorialspoint; public class GenericsTester { public static void main(String[] args) { //type inference Box<Integer> integerBox = new Box<>(); Box<String> stringBox = new Box<String>(); integerBox.add(new Integer(10)); stringBox.add(new String("Hello World")); System.out.printf("Integer Value :%dn", integerBox.get()); System.out.printf("String Value :%sn", stringBox.get()); } } class Box<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } } Output :- Integer Value :10 String Value :Hello World
  • 28. Bounded Type Parameter There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for. How to Declare a Bounded Type Parameter in Java? 1. List the type parameter’s name, 2. Along with the extends keyword 3. And by its upper bound. (which in the below example c is A.)  Syntax :- <T extends superClassName>  Multiple Bounds :- Bounded type parameters can be used with methods as well as classes and interfaces. Java Generics supports multiple bounds also, i.e., In this case, A can be an interface or class. If A is class, then B and C should be interfaces. We can’t have more than one class in multiple bounds.  Syntax :- <T extends superClassName & Interface>
  • 29. Program – Bounded Type Parameter public class MaximumTest { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; if(y.compareTo(max) > 0) { max = y; } if(z.compareTo(max) > 0) { max = z; } return max; } public static void main(String args[]) { System.out.printf("Max of %d, %d and %d is %dnn", 3, 4, 5, maximum( 3, 4, 5 )); System.out.printf("Max of %.1f,%.1f and %.1f is %.1fnn", 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 )); System.out.printf("Max of %s, %s and %s is %sn","pear", "apple", "orange", maximum("pear", "apple", "orange")); } } Output :- Max of 3, 4 and 5 is 5 Max of 6.6,8.8 and 7.7 is 8.8 Max of pear, apple and orange is pear
  • 30. Wild Card in Java The ? (question mark) symbol represents the wildcard element. It means any type. If we write <? extends Number>, it means any child class of Number, e.g., Integer, Float, and double. Now we can call the method of Number class through any child class object. We can use a wildcard as a type of a parameter, field, return type, or local variable. However, it is not allowed to use a wildcard as a type argument for a generic method invocation, a generic class instance creation, or a supertype. They are of three types :- 1. Upper Bounded Wildcard 2. Unbounded Wildcard 3. Lower Bounded Wildcard
  • 31. Program for Wildcard in Java Generic import java.util.*; abstract class Shape{ abstract void draw(); } class Rectangle extends Shape{ void draw(){System.out.println("drawing rectangle");} } class Circle extends Shape{ void draw(){System.out.println("drawing circle");} } class GenericTest{ public static void drawShapes(List<? extends Shape> lists){ for(Shape s:lists){ s.draw(); instance } } public static void main(String args[]){ List<Rectangle> list1=new ArrayList<Rectangle>(); list1.add(new Rectangle()); List<Circle> list2=new ArrayList<Circle>(); list2.add(new Circle()); list2.add(new Circle()); drawShapes(list1); drawShapes(list2); }} Output :- drawing rectangle drawing circle drawing circle
  • 32. Types of Wildcard 1. Upper Bounded Wildcards :- The purpose of upper bounded wildcards is to decrease the restrictions on a variable. It restricts the unknown type to be a specific type or a subtype of that type. It is used by declaring wildcard character ("?") followed by the extends or implements keyword, followed by its upper bound. Syntax :- List<? extends Number> Here, extends, is a keyword. Number, is a class present in java.lang package 2. Lower Bounded Wildcards :- The purpose of lower bounded wildcards is to restrict the unknown type to be a specific type or a supertype of that type. It is used by declaring wildcard character ("?") followed by the super keyword, followed by its lower bound. Syntax :- List<? super Integer> Here, super, is a keyword. Integer, is a wrapper class. 3. Unbounded Wildcards :- This type represents the list of an unknown type such as List<?>. This approach can be useful in the following scenarios: - • When the given method is implemented by using the functionality provided in the Object class. • When the generic class contains the methods that don't depend on the type parameter.
  • 33. Program for Upper Bounded Wildcard // Java program to demonstrate Upper Bounded Wildcards import java.util.Arrays; import java.util.List; class WildcardDemo { public static void main(String[] args) { List<Integer> list1 = Arrays.asList(4, 5, 6, 7); System.out.println("Total sum is:" + sum(list1)); List<Double> list2 = Arrays.asList(4.1, 5.1, 6.1); 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
  • 34. Program for Lower Bounded Wildcard // Java program to demonstrate Lower Bounded Wildcards import java.util.Arrays; import java.util.List; class WildcardDemo { public static void main(String[] args) { List<Integer> list1 = Arrays.asList(4, 5, 6, 7); printOnlyIntegerClassorSuperClass(list1); List<Number> list2 = Arrays.asList(4, 5, 6, 7); printOnlyIntegerClassorSuperClass(list2); } public static void printOnlyIntegerClassorSuperClass( List<? super Integer> list) { System.out.println(list); } } Output :- [4, 5, 6, 7] [4, 5, 6, 7]
  • 35. Program for Unbounded Wildcard // Java program to demonstrate Unbounded wildcard import java.util.Arrays; import java.util.List; class unboundedwildcardemo { public static void main(String[] args) { List<Integer> list1 = Arrays.asList(1, 2, 3); 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]
  • 36. Type Erasure Generics are used for tighter type checks at compile time and to provide a generic programming. To implement generic behaviour, java compiler apply type erasure. Type erasure is a process in which compiler replaces a generic parameter with actual class or bridge method. In type erasure, compiler ensures that no extra classes are created and there is no runtime overhead.  Type Erasure rules :-  Replace type parameters in generic type with their bound if bounded type parameters are used.  Replace type parameters in generic type with Object if unbounded type parameters are used.  Insert type casts to preserve type safety.  Generate bridge methods to keep polymorphism in extended generic types.
  • 37. Restrictions on Generics To use Java generics effectively, you must consider the following restrictions :-  Cannot Instantiate Generic Types with Primitive Types  Cannot Create Instances of Type Parameters  Cannot Declare Static Fields Whose Types are Type Parameters  Cannot Use Casts or instanceof With Parameterized Types  Cannot Create Arrays of Parameterized Types  Cannot Create, Catch, or Throw Objects of Parameterized Types  Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same Raw Type