The document discusses Java collections and generics. It provides an overview of collection interfaces like List, Set, Queue and their implementations like ArrayList, LinkedList, HashSet. It also covers generics concepts like type parameters, generic methods and constructors. Sample programs demonstrate how to use ArrayList, PriorityQueue and generic methods. The key benefits of collections framework are reducing programming effort and increasing program speed and quality.
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion, etc. can be achieved by Java Collections.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque, etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet, etc.).
To learn important concept of Collection and its handling plus its advantages and different class & child class of Collection and their implementations. Important interview questions of the collection.
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Sagar Verma
Collection Framework in Java,Generics,Input-Output in Java,Serialization,Inner Classes
Collection Framework in Java
The Collections Framework - Set Interface- List Interface - Map Interface - Queue Interface -Sorting collections using utility methods
equals () and hash Code contract in Java collections
Overriding equals and hash Code methods in Java
Generics
Generics for Collections, class and methods
Input-Output in Java
What is a stream? ,Bytes vs. Characters, Java IO API ,Reading a file; writing to a file using various APIs
Reading User input from console , PrintWriter Class
Serialization
Object Serialization , Serializable Interface , De-Serializable
Inner Classes
Inner Classes ,Member Classes, Local Classes, Anonymous Classes, Static Nested Classes
The Collection in Java is a framework that provides an architecture to store and manipulate the group of objects.
All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion, etc. can be achieved by Java Collections.
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque, etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet, etc.).
To learn important concept of Collection and its handling plus its advantages and different class & child class of Collection and their implementations. Important interview questions of the collection.
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...Sagar Verma
Collection Framework in Java,Generics,Input-Output in Java,Serialization,Inner Classes
Collection Framework in Java
The Collections Framework - Set Interface- List Interface - Map Interface - Queue Interface -Sorting collections using utility methods
equals () and hash Code contract in Java collections
Overriding equals and hash Code methods in Java
Generics
Generics for Collections, class and methods
Input-Output in Java
What is a stream? ,Bytes vs. Characters, Java IO API ,Reading a file; writing to a file using various APIs
Reading User input from console , PrintWriter Class
Serialization
Object Serialization , Serializable Interface , De-Serializable
Inner Classes
Inner Classes ,Member Classes, Local Classes, Anonymous Classes, Static Nested Classes
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Java Collections” will talk about the complete hierarchy of Collections Frameworks in Java. It will walk you through the various fundamentals of collections like Lists, Queue, Sets, Interfaces etc. Through this tutorial you will learn the following topics:
Java Collection Framework
Collection Framework Hierarchy
Interfaces
List
Queue
Set
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
Discuss the characteristics of ArrayList, LinkedList, and Vector and.pdfinfo785431
Discuss the characteristics of ArrayList, LinkedList, and Vector and their differences
Solution
Hi Please find my explanation:
ArrayList
Think of this as a growable array. It gives you fast iteration and fast random access. To state
the obvious: it is an ordered collection (by index), but not sorted.ArrayList supports fast
(generally constant time) random access.
Choose this over a LinkedList when you need fast iteration but aren\'t as likely to be doing a
lot of insertion and deletion.
Linked List:
A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-
linked to one another. This linkage gives you new methods (beyond what you get from the List
interface) for adding and removing from the beginning or end, which makes it an easy choice for
implementing a stack or queue. Keep in mind that a LinkedList may iterate more slowly than an
ArrayList, but it\'s a good choice when you need fast insertion and deletion. As of Java 5, the
LinkedList class has been enhanced to implement the java.util.Queue interface. As such, it now
supports the common queue methods: peek(), poll(), and offer().
Vector:
A Vector is basically the same as an ArrayList, but Vector methods are syn-chronized for
thread safety. You\'ll normally want to use ArrayList instead of Vector because the synchronized
methods add a performance hit you might not need. And if you do need thread safety, there are
utility methods in class Collections that can help. Vector is the only class other than ArrayList to
implement RandomAccess.
Vector is a holdover from the earliest days of Java; Vector and Hashtable were the two
original collections, the rest were added with Java 2 versions 1.2 and 1.4..
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Edureka!
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Java Collections” will talk about the complete hierarchy of Collections Frameworks in Java. It will walk you through the various fundamentals of collections like Lists, Queue, Sets, Interfaces etc. Through this tutorial you will learn the following topics:
Java Collection Framework
Collection Framework Hierarchy
Interfaces
List
Queue
Set
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
Discuss the characteristics of ArrayList, LinkedList, and Vector and.pdfinfo785431
Discuss the characteristics of ArrayList, LinkedList, and Vector and their differences
Solution
Hi Please find my explanation:
ArrayList
Think of this as a growable array. It gives you fast iteration and fast random access. To state
the obvious: it is an ordered collection (by index), but not sorted.ArrayList supports fast
(generally constant time) random access.
Choose this over a LinkedList when you need fast iteration but aren\'t as likely to be doing a
lot of insertion and deletion.
Linked List:
A LinkedList is ordered by index position, like ArrayList, except that the elements are doubly-
linked to one another. This linkage gives you new methods (beyond what you get from the List
interface) for adding and removing from the beginning or end, which makes it an easy choice for
implementing a stack or queue. Keep in mind that a LinkedList may iterate more slowly than an
ArrayList, but it\'s a good choice when you need fast insertion and deletion. As of Java 5, the
LinkedList class has been enhanced to implement the java.util.Queue interface. As such, it now
supports the common queue methods: peek(), poll(), and offer().
Vector:
A Vector is basically the same as an ArrayList, but Vector methods are syn-chronized for
thread safety. You\'ll normally want to use ArrayList instead of Vector because the synchronized
methods add a performance hit you might not need. And if you do need thread safety, there are
utility methods in class Collections that can help. Vector is the only class other than ArrayList to
implement RandomAccess.
Vector is a holdover from the earliest days of Java; Vector and Hashtable were the two
original collections, the rest were added with Java 2 versions 1.2 and 1.4..
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Read| The latest issue of The Challenger is here! We are thrilled to announce that our school paper has qualified for the NATIONAL SCHOOLS PRESS CONFERENCE (NSPC) 2024. Thank you for your unwavering support and trust. Dive into the stories that made us stand out!
Unit 8 - Information and Communication Technology (Paper I).pdfThiyagu K
This slides describes the basic concepts of ICT, basics of Email, Emerging Technology and Digital Initiatives in Education. This presentations aligns with the UGC Paper I syllabus.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
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