0% found this document useful (0 votes)
21 views49 pages

5 Generics

Ldco Unit 5

Uploaded by

lesterxd60
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views49 pages

5 Generics

Ldco Unit 5

Uploaded by

lesterxd60
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Generics

Ms. Kashmira Jayakar


• 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.
Advantage 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, 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. For
example,
• public <T> void genericsMethod (T data) {...}
• Here, we have created a generics method. This
same method can be used to perform
operations on integer data, string data, and so
on.
• 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.
• Generics in Java are similar to templates in
C++. For example, classes like HashSet,
ArrayList, HashMap, etc., use generics very
well.
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 Class
• Like C++, we use <> to specify parameter types
in generic class creation. To create objects of a
generic class, we use the following syntax.
• // To create an instance of generic class
BaseType <Type> obj = new BaseType
<Type>()Note: In Parameter type we can not
use primitives like ‘int’,’char’ or ‘double’.
// Java program to show multiple
// type parameters in Java Generics
// We use < > to specify Parameter type
class Test<T, U>
{
T obj1; // An object of type T
U obj2; // An object of type U
// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

// To print objects of T and U


public void print()
{
System.out.println(obj1);
System.out.println(obj2);
} }

// Driver class to test above


class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj =
new Test<String, Integer>("GfG", 15);

obj.print();
} }
• OutputGfG 15
Collections in Java
• 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.

• A Collection represents a single unit of


objects, i.e., a group.
• 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).
Hierarchy of Collection Framework
core collection interfaces:
• Collection — the root of the collection hierarchy. A
collection represents a group of objects known as
its elements. The Collection interface is the least
common denominator that all collections
implement and is used to pass collections around
and to manipulate them when maximum
generality is desired. Some types of collections
allow duplicate elements, and others do not. Some
are ordered and others are unordered. The Java
platform doesn't provide any direct
implementations of this interface but provides
implementations of more specific sub interfaces,
such as Set and List
core collection interfaces:
• Set — a collection that cannot contain
duplicate elements. This interface models the
mathematical set abstraction and is used to
represent sets, such as the cards comprising a
poker hand, the courses making up a student's
schedule, or the processes running on a
machine.
core collection interfaces:
• List — an ordered collection (sometimes
called a sequence). Lists can contain duplicate
elements. The user of a List generally has
precise control over where in the list each
element is inserted and can access elements
by their integer index (position). If you've
used Vector, you're familiar with the general
flavor of List
core collection interfaces:
• Queue — a collection used to hold multiple
elements prior to processing. Besides
basic Collection operations, a Queue provides
additional insertion, extraction, and
inspection operations.
core collection interfaces:
• Deque — a collection used to hold multiple
elements prior to processing. Besides
basic Collection operations, a Deque provides
additional insertion, extraction, and
inspection operations.
No. Method Description

1 public boolean hasNext() It returns true if the iterator has more


elements otherwise it returns false.

2 public Object next() It returns the element and moves the cursor
pointer to the next element.

3 public void remove() It removes the last elements returned by the


iterator. It is less used.
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.
• To instantiate the List interface, we must use :
• List <data-type> list1= new ArrayList();
• List <data-type> list2 = new LinkedList();
• List <data-type> list3 = new Vector();
• List <data-type> list4 = new Stack();
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
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arrayl
ist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
• Output
Ravi
Vijay
Ravi
Ajay
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.
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
Java ArrayList class
Java ArrayList class
• Java ArrayList class uses a dynamic array for
storing the elements. It is like an array, but
there is no size limit. We can add or remove
elements anytime. So, it is much more flexible
than the traditional array. It is found in
the java.util package. It is like the Vector in
C++.
Java ArrayList class
• The ArrayList in Java can have the duplicate
elements also. It implements the List interface
so we can use all the methods of the List
interface here. The ArrayList maintains the
insertion order internally.

• It inherits the AbstractList class and


implements List interface.
Java ArrayList class
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.
• Java ArrayList class is non synchronized.
• Java ArrayList allows random access because the array
works on an index basis.
• In ArrayList, manipulation is a little bit slower than the
LinkedList in Java because a lot of shifting needs to
occur if any element is removed from the array list.
• We can not create an array list of the primitive types,
such as int, float, char, etc. It is required to use the
required wrapper class in such cases.
Java ArrayList class
• arrayList<int> al = ArrayList<int>(); // does not
work
• ArrayList<Integer> al = new ArrayList<Integer>
(); // works fine
• Java ArrayList gets initialized by the size. The
size is dynamic in the array list, which varies
according to the elements getting added or
removed from the list.
Java ArrayList class
• ArrayList class declaration

public class ArrayList<E> extends AbstractList<


E> implements List<E>, RandomAccess, Clone
able, Serializable
Java ArrayList class

Constructors of ArrayList
Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? It is used to build an array list that is initialized with


extends E> c) the elements of the collection c.

ArrayList(int capacity) It is used to build an array list that has the specified
initial capacity.
Methods of ArrayList

Method Description

void add(int index, E element) It is used to insert the specified


element at the specified position in a
list.
boolean add(E e) It is used to append the specified
element at the end of a list.
void clear() It is used to remove all of the elements
from this list.
boolean isEmpty() It returns true if the list is empty,
otherwise false.
Java Non-generic Vs. Generic
Collection
• Let's see the old non-generic example of creating
a Java collection.
ArrayList list=new ArrayList();//creating old non-
generic arraylist
• Let's see the new generic example of creating
java collection.
ArrayList<String> list=new ArrayList<String>();//cre
ating new generic arraylist
import java.util.*;
public class ArrayListExample2{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Mango");//Adding object in arraylist
list.add("Apple");
list.add("Banana");
list.add("Grapes");
//Traversing list through Iterator
Iterator itr=list.iterator();//getting the Iterator
while(itr.hasNext()){//check if iterator has the elements
System.out.println(itr.next());//printing the element and move to nex
t
}
}
}
Java LinkedList class
Java LinkedList class
• Java LinkedList class uses a doubly linked list
to store the elements. It provides a linked-list
data structure. It inherits the AbstractList class
and implements List and Deque interfaces.
Java LinkedList class
• The important points about Java LinkedList
are:
• Java LinkedList class can contain duplicate
elements.
• Java LinkedList class maintains insertion order.
• Java LinkedList class is non synchronized.
• In Java LinkedList class, manipulation is fast
because no shifting needs to occur.
• Java LinkedList class can be used as a list, stack
or queue.
LinkedList class declaration

• public class LinkedList<E> extends AbstractSe


quentialList<E> implements List<E>, Deque<E
>, Cloneable, Serializable
Constructors of Java LinkedList

Constructor Description

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

LinkedList(Collection< It is used to construct a list containing the elements of


? extends E> c) the specified collection, in the order, they are returned
by the collection's iterator.
Set Interface
Set Interface
• The Set Interface is present in java.util package
and extends the Collection interface.
• It is an unordered collection of objects in which
duplicate values cannot be stored.
• It is an interface that implements the
mathematical set.
• This interface contains the methods inherited
from the Collection interface and adds a feature
that restricts the insertion of the duplicate
elements.
Set Interface
• // Obj is the type of the object to be stored in
Set
Set<Obj> set = new HashSet<Obj> ();
Set Interface
Method Description

This method is used to add a specific element to the set. The function adds the element
add(element) only if the specified element is not already present in the set else the function returns
False if the element is already present in the Set.

This method is used to append all of the elements from the mentioned collection to the
addAll(collection)
existing set. The elements are added randomly without following any specific order.

This method is used to remove all the elements from the set but not delete the set. The
clear()
reference for the set still exists.

contains(element) This method is used to check whether a specific element is present in the Set or not.

This method is used to check whether the set contains all the elements present in the
containsAll(collectio
given collection or not. This method returns true if the set contains all the elements and
n)
returns false if any of the elements are missing.
Method Description

This method is used to return the iterator of the set. The elements from the set are returned
iterator()
in a random order.

You might also like