[Go to site: main page, start]

0% found this document useful (0 votes)
3 views68 pages

5th Module Java

The document provides an overview of the Java Collections Framework, detailing its structure, including key interfaces such as Collection, List, Set, and Map, along with their implementations like ArrayList, LinkedList, HashSet, and HashMap. It explains the functionality of iterators, comparators, and the motivation for generic programming, highlighting how these components work together to manage and manipulate groups of objects efficiently. Additionally, examples of code snippets illustrate the practical use of these classes and interfaces in Java programming.

Uploaded by

Riyaz Ahamed
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)
3 views68 pages

5th Module Java

The document provides an overview of the Java Collections Framework, detailing its structure, including key interfaces such as Collection, List, Set, and Map, along with their implementations like ArrayList, LinkedList, HashSet, and HashMap. It explains the functionality of iterators, comparators, and the motivation for generic programming, highlighting how these components work together to manage and manipulate groups of objects efficiently. Additionally, examples of code snippets illustrate the practical use of these classes and interfaces in Java programming.

Uploaded by

Riyaz Ahamed
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

Topics

• Collection
• Collection Interface –List, Set, Map, Collection Classes- Array List, HashSet
• HashMap
• Using an Iterator- For-Each-Comparators
• Wrapper classes
• Motivation for Generic Programming
• Generic Classes and Methods
• Bounded Types
• Wildcard Arguments
• Generic Constructors and Interfaces

2
Collections

3
Collections
• A Collection represents a single unit of objects, i.e., a group.
• The Collection is a framework that provides an architecture to store
and manipulate the group of objects.
• Java Collections can achieve all the operations performing on a data
such as searching, sorting, insertion, manipulation, and deletion.

Two “root” interfaces of Java collection Framework


• Collection interface ([Link])
• Map interface ([Link])

4
Collections
Framework:

• A framework is a set of classes and interfaces provide a ready-made


architecture.

• Used to implement a new feature or a class, there is no need to define a


framework.

• Java Collection framework represents many interfaces (Set, List, Queue,


Deque) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet,
LinkedHashSet, TreeSet).

5
Collection Framework Hierarchy

Extends: Extends is a
keyword that is used for
developing inheritance
between two classes and
two interfaces.

Implements: Implements
is a keyword used for
developing inheritance
between class and
interface.
6
Collection Interface
• Interface contains methods and variables, but the methods only declared in an interface
(only method signature, no method definition).

• Collection interface extends the iterable interface and is implemented by all the classes
in the collection framework.

• This interface contains all the basic methods such as adding the data into the collection,
removing the data, clearing the data, etc.
a) add(Object) – This method is used to add an object to the collection.
b) addAll(Collection c) – It adds all the elements in the given collection to this collection.
c) clear() – This method removes all the elements from this collection.
d) remove(Object o) – It removes the given object from the collection. If duplicate values
exist, then removes the first occurrence of the object

• All these methods are implemented by all the classes. Existence of these methods in this
interface ensures the methods are universal for all the collections i.e., collection interface
builds a foundation on which the collection classes are implemented. 7
List Interface
• List Interface is a child interface of the collection interface.
• It is dedicated to the data of the list type in which user can store all the ordered collection of
the objects. This also allows duplicate data.
• The classes implements the List Interface are ArrayList, Vector, Stack, LinkedList, etc.
• Since all the subclasses implement the list, user can instantiate a list object with any of these
classes.

Syntax:
• ArrayList < data_type > x = new ArrayList < data_type > ();
• LinkedList < data_type > y = new LinkedList < data_type > ();
• Vector < data_type > z = new Vector < data_type > ();
• Stack < data_type > z = new Stack < data_type > ();

Create an ArrayList

ArrayList <String> list1 = new ArrayList<String> ();

8
ArrayList Class
• It implements a dynamic array by extending AbstractList.

• ArrayList provides us with dynamic arrays in Java.

• The size of an ArrayList is changes automatically i.e., grows or shrinks


depends on the object's addition and deletion.

• Java ArrayList allows us to randomly access the list.

• User needs a wrapper class for such cases

9
ArrayList Example
import [Link].*;
import [Link].*;
class Main
{
public static void main (String[]args)
{
// Declaring the ArrayList
ArrayList < Integer > al = new ArrayList < Integer > ();
// Appending new elements
for (int i = 100; i <= 105; i++)
[Link] (i);
[Link] (al);
// Remove element at index 3
[Link] (3);
[Link] (al);
for (int i = 0; i < [Link] (); i++)
[Link] ([Link] (i) + " ");
}
} 10
Linked List Class
• LinkedList implements the Collection interface.

• LinkedList class is an implementation of the LinkedList data structure.

• It is a linear data structure where the elements are not stored in contiguous locations and
every element is a separate object with a data part and address part.

• The elements are linked using pointers and addresses. Each element is known as a node.

• 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.
11
Linked List Example 1
import [Link].*;
public class Main
{
public static void main (String args[])
{
LinkedList < String > al = new LinkedList < String > ();
[Link] ("Sai");
[Link] ("Srinivas");
[Link] ("Pavan");
[Link] ("Pavani");
Iterator < String > itr = [Link] ();
while ([Link] ())
{
[Link] ([Link] ());
}
}
}

12
Linked List Example 2
import [Link].*;
import [Link].*;
class Main
{
public static void main (String[]args)
{
LinkedList < Integer > x = new LinkedList < Integer > ();
for (int i = 1; i <= 5; i++)
[Link] (i);
[Link] (x);
[Link] (3);
[Link] (x);
}
}

13
Vector Class
• Vector uses a dynamic array to store the data elements.

• It is identical to ArrayList in terms of implementation.


• Difference between a vector and an ArrayList: ➢ Vector is synchronized and an ArrayList is non-synchronized

import [Link].*;
public class Main
{
public static void main (String args[])
{
Vector < String > v = new Vector < String > ();
[Link] ("Sai");
[Link] ("Srinivas");
[Link] ("Pavan");
Iterator < String > itr = [Link]();
while ([Link]())
{
[Link] ([Link]()); 14
}}}
Vector Class
import [Link].*;
import [Link].*;
class Main
{
public static void main (String[]args)
{
Vector < Integer > v = new Vector < Integer > ();
for (int i = 101; i <= 105; i++)
[Link] (i);
[Link] (v);
[Link] (3);
[Link] (v);
}
}

15
Stack Class
• The stack is the subclass of Vector.

• Stack class implements the Stack data structure based on last-in-first-out.

• In addition to the push and pop operations, the class provides three more functions
of empty, search and peek

16
Stack Class
import [Link].*;
public class Main
{
public static void main (String args[]) {
Stack < String > stack = new Stack < String > ();
[Link] ("Sai");
[Link] ("Sree");
[Link] ("Felix");
Iterator < String > itr = [Link]();
while ([Link]())
{
[Link] ([Link]());
}
[Link] ();
itr = [Link]();
[Link] ("After Popping");
while ([Link]())
{
[Link] ([Link]());
}}} 17
Set Interface
• Set Interface extends the Collection interface.

• It represents the unordered set of elements .

• It cannot store the duplicate items.

• User can store at most one null value in Set.

• Set interface is implemented by HashSet, LinkedHashSet, and TreeSet.

• HashSet <data-type> s1 = new HashSet<data-type>();


• LinkedHashSet <data-type> s2 = new LinkedHashSet<data-type>();
• TreeSet <data-type> s3 = new TreeSet<data-type>();

18
HashSet Class
• HashSet class implements Set Interface.
• It represents the collection that uses a hash table as a storage.
• Hashing is used to store the unique elements in the HashSet.
import [Link].*;
public class Main
{
public static void main (String args[]) {
//CreatingHashSet
HashSet < String > set = new HashSet < String > ();
[Link] ("Jai");
[Link] ("Vineet");
[Link] ("Raj");
[Link] ("Raj"); //Duplicate
//Traversingelements
Iterator < String > itr = [Link] ();
while ([Link] ())
{
[Link] ([Link] ());
}}} 19
Map Interface
• A map is a data structure that supports the key-value pair mapping for the data.

• Map doesn’t support duplicate keys because the same key cannot have multiple
mappings.

• A map is useful if there is a data, user can perform operations based on the key.

• Map interface is implemented by various classes such as HashMap, TreeMap etc.

• Instantiate a map object with any of these classes due to all the subclasses
implement the map

• HashMap <data-type> h1 = new HashMap <data-type> ();


• TreeMap <data-type> t1 = new TreeMap <data-type> ();

20
HashMap Class
• Map interface is frequently implemented by HashMap.
• It stores the data in (Key, Value) pairs.
• To access a value in a HashMap, user must know its key.
• HashMap uses a technique called Hashing which converts a large String to small String that
represents the same String.
• So, the indexing and search operations are faster. HashSet also uses HashMap internally

[Link] Interface:
• Entry is the sub interface of Map. It can be accessed it by [Link] name.
• It returns a collection-view of the map, whose elements belong to this class.
• It provides methods to get key and value.

• [Link]() - Converting to Set


• [Link] m : [Link]() - Converting to [Link] to get key and value separately

21
HashMap Class - Example
import [Link].*;
public class Main
{
public static void main (String args[])
{
HashMap < Integer, String > h = new HashMap < Integer, String > ();
[Link] (1, "Hi");
[Link] (2, "Welcome");
[Link] (3, "To VIT-AP");
// Finding the value for a key
[Link] ("Value for 1 is " + [Link] (1));
// Traversing
for ([Link] < Integer, String > e:[Link] ())
[Link] ([Link] () + " " + [Link] ());
}
}

22
Iterator Interface
• Iterator interface retrieves elements one by one from collection.

• It is iterating the elements of an object in a forward direction only.

• It uses the methods in while loop

Methods in Iterator interface


• hasNext() - It returns true if the iterator has more elements, otherwise returns false.

• next() - It returns the current element and moves the cursor pointer to the next element.

• remove() - It removes the last element returned by the iterator.

23
Iterator Example
import [Link].*;
import [Link].*;
class Main
{
public static void main (String[]args) {
ArrayList < String > al = new ArrayList < String > ();
[Link] ("Sai");
[Link] ("Srinivas");
[Link] ("Pavan");
Iterator < String > itr = [Link] ();
while ([Link] ()) {
[Link] ([Link] ());
// deletes last element
}
Iterator < String > i = [Link] ();
String str = "";
while ([Link] ()) {
str = (String) [Link] ();
if ([Link] ("Sai")) {
[Link] ();
[Link] ("\nThe element is removed");
break; } }
while ([Link] ()) {
[Link] ([Link] ());
} }
}
24
Iterator Interface
• The Iterable interface is the root interface for all the collection classes.

• The Collection interface extends the Iterable interface.

• To use for loop to elements, the class must implement the iterable interface.

• for-each loop uses iterable interface internally for iterating over objects of the implemented class.

• Iterables does not have a current state, rather it delivers an iterator method.

• It contains only one abstract method is the iterator() that internally called by iterable interface.

Steps to implement:
• Implement an iterable interface using the class whose object needs access to for-each loop.
• Any class that implements the iterable interface should Override the iterator() method provide by iterable
interface.
• The iterable does not maintain a current state so return an instance of iterator() method
25
import [Link]; // Method to check if there is a next element
import [Link]; @Override
public boolean hasNext() {
// Generic class Simple implementing Iterable interface return cursor < [Link]();
class Simple<T> implements Iterable<T> { }
private T[] elements; // Array to hold the elements
private int size; // Size of the array // Method to get the next element
@Override
// Constructor to initialize the elements and size public T next() {
public Simple(T[] elements) { if (!hasNext()) {
[Link] = elements; throw new NoSuchElementException();
[Link] = [Link]; } }
return [Link]()[cursor++];
// Overriding the iterator method to return an instance of CustomIterator }
@Override
public Iterator<T> iterator() { // Method to remove an element (not implemented)
return new CustomIterator<>(this); } @Override
public void remove() {
// Getter for the elements array throw new UnsupportedOperationException();
public T[] getElements() { }
return elements; } }
}
// Getter for the size class Main {
public int getSize() { public static void main(String[] args) {
return size; } Integer[] numbers = {1, 2, 3, 4, 5}; // Create an array
// CustomIterator class implementing Iterator interface of integers
private class CustomIterator<T> implements Iterator<T> { Simple<Integer> simple = new Simple<>(numbers); //
private int cursor; // Pointer to track the current position Create a Simple object with the array
private Simple<T> simple; // Reference to the Simple object
// Iterate over the Simple object using the for-each loop
// Constructor to initialize the Simple reference and cursor for (Integer num : simple) {
public CustomIterator(Simple<T> simple) { [Link](num); // Print each element
[Link] = simple; }
[Link] = 0; // Initialize cursor to the start } }
} 26
Comparator Interface
• A comparator interface is used to order (ascending) the objects of user-defined classes.
• A comparator object is capable of comparing two objects of two different classes.

❑ Two methods in Comparator: a) compare()


b) equal()

❑ Example: int compare(T object1, T object2)

❑ The compare method returns:


• a negative number if object1 is less than object2,
• zero if object1 and object2 are equal, and
• a positive number if object1 is greater than the object2.
boolean equals(Object obj)
• returns true if the specified object is equal to this comparator object. 27
Comparator Interface: Example
import [Link].*; List<Student> ar = new ArrayList<Student>();
class Student { [Link](new Student(111, "bbbb"));
int rollno; [Link](new Student(131, "aaaa"));
String name; [Link](new Student(121, "cccc"));
public Student(int rollno, String name){ [Link](ar, new Sortbyroll());
[Link] = rollno; [Link]("\nSorted by rollno");
[Link] = name;}
for (int i = 0; i < [Link](); i++)
public String toString(){
[Link]([Link](i));
return [Link] + " " + [Link] ;
}} [Link](ar, new Sortbyname());
class Sortbyroll implements Comparator<Student> { [Link]("\nSorted by name");
// ascending order of roll number for (int i = 0; i < [Link](); i++)
public int compare(Student a, Student b) [Link]([Link](i));
{ }
return [Link] - [Link]; }
}
}
class Sortbyname implements Comparator<Student> {
// ascending order of name
public int compare(Student a, Student b)
{
return [Link]([Link]);
}
}
class Main {
public static void main(String[] args)
{
28
Wrapper class

29
Wrapper class in Java
• The wrapping is the mechanism of converting primitive (int, char, float, etc) into object and object into
primitive.
• Java is an OOP language that deals with objects mostly in Collections, Serialization, Synchronization, etc.
• Ex: Using primitive data type
int i = 10;
• The object representation Using wrapper class:
Integer ref = new Integer(i);

Use of Wrapper classes in Java


• All Collection classes in Java can store only Objects
• The [Link] package provides the utility classes to deal with objects.
• Java synchronization works with objects in Multithreading.
• Primitive data types cannot be stored directly in these classes and hence the primitive
values needs to be converted to objects. Then represent as an object
30
Wrapper class in Java
• Java API provides a set of classes that makes the wrapping easier are called wrapper classes.

• For all the primitive data types, there are corresponding wrapper classes.

• Storing primitive types in the form of objects affects the performance in terms of memory
and speed

Example:
• Representing an integer via a wrapper takes about 12-16 bytes, compared to 4 in an
actual integer.

• Also, retrieving the value of an integer uses the method [Link]().

31
Wrapper class Hierarchy in Java

32
Primitive data type and Corresponding Wrapper classes

Primitive Wrapper Class Constructor Argument


boolean Boolean boolean or String
byte Byte byte or String
char Character char
int Integer int or String
float Float float, double or String
double Double double or String
long Long long or String
short Short short or String
33
Common Methods of numerical wrapper classes
byteValue()
• Returns the value of the invoking object as a byte.
doubleValue()
• Returns the value of the invoking object as a double.
floatValue()
• Returns the value of the invoking object as a float.
longValue()
• Returns the value of the invoking object as a long.
shortValue()
• Returns the value of the invoking object as a short. 34
Integer Wrapper class
• Class Integer is a wrapper for values of type int.
• Integer objects can be constructed with an int value, or a string containing an int value

❑ The constructors for Integer:


• Integer( int num)
• Integer(String str) throws NumberFormatException

❑ Some methods of the Integer class:

• static int parseInt(String str) throws NumberFormatException


• int intValue( ) - returns the value of the invoking object as an int value

35
Integer Wrapper class
public static String toBinaryString(int i)
• find base 2(with no extra leading 0s (zeros)) for the given int.
public static String toOctalString(int i)
• find base 8 (with no extra leading 0s (zeros)) for the given int.
public static String toHexString(int i)
• find base 16(with no extra leading 0s (zeros)) for the given int.

public class Main


{
public static void main (String args[])
{
int x = 100;
[Link] ([Link] (x));
[Link] ([Link] (x));
[Link] ([Link] (x));
}}
36
Float Wrapper class
• Class Float is a wrapper for values of type float.
• Float objects can be constructed with a float value, or a string containing a float value

❑ The constructors for Float:


• Float (float num)
• Float(String str) throws NumberFormatException

❑ Some methods of the Float class:

• static float parse float (String str) throws NumberFormatException


• float floatValue( ) - returns the value of the invoking object as a float value

37
Character Wrapper class
• Character class is a wrapper class for character data types

❑ The constructors for Character:


Character(char c)

• Here, c specifies the character to be wrapped by the Character object

• After a Character object is created, user can retrieve the primitive character value
from it using:

char charValue( )

38
public class Main {
public static void main (String ar[]) {
String input = "Hi, Sachin Is My Favorite Cricketer!";
char[] a = [Link] ();
int alpha = 0, upper = 0, lower = 0, symbol = 0, digit = 0, space = 0;
for (char c:a)
{
if ([Link] (c))
Character alpha++;
if ([Link] (c))
Wrapper class digit++;
if ([Link] (c))
- Example upper++;
if ([Link] (c))
lower++;
if ([Link] (c))
space++;
}
symbol = [Link] - (alpha + digit + space);
[Link] ("[Link] alphabets " + alpha);
[Link] ("[Link] digits " + digit);
[Link] ("[Link] upper case " + upper);
[Link] ("[Link] lower case " + lower);
[Link] ("[Link] spaces " + space);
[Link] ("[Link] symbols " + symbol);
}
}
39
Boolean Wrapper class
• The Boolean class is a wrapper class for boolean values

❑ The constructors for Boolean:


Boolean(boolean Value)
• Value can be either true or false

Boolean(String str)
• The object created by constructor have the value true or false
depending upon the string value in str is “true” or “false”.

• The value of str can be in upper case or lower case

40
Convert primitive datatype to Wrapper (Autoboxing)
class Main {
public static void main (String[]args) {
// create primitive types
int a = 10;
double b = 100.12;
Integer Obj1 = [Link] (a); //converts into wrapper objects
Double Obj2 = [Link] (b);
if (Obj1 instanceof Integer)
{
[Link] ("An object of Integer is created.");
}
if (Obj2 instanceof Double)
{
[Link] ("An object of Double is created.");
}
}
}

41
Convert wrapper to primitive (Unboxing)
public class Main
{
public static void main (String args[])
{
//Converting Integer to int
Integer a = new Integer (3);
int i = [Link] (); //converts Integer to int explicitly
int j = a; //unboxing, now compiler writes [Link]() internally
[Link] (a + " " + i + " " + j);
}
}

42
Generic Programming

43
Generics
• A class, interface, or method that operates on a parameterized type is called generic.
• Generics is used to create a single class, interface, and method that can be used with
different types of data (objects).
• Generics means parameterized types.

Advantage of Generics:

➢ Type-safety: It holds only a single type of objects in generics. It doesn’t allow to


store other objects
//With Generics, it needs the type of object
//Without Generics //to store.
List al = new ArrayList(); List<Integer> al=new ArrayList<Integer>();
[Link](5); [Link](10);
[Link]("10"); [Link]("10"); // compile-time error

44
Advantages of Generics
Type casting is not required: There is no need to typecast the object
//Without generics //With Generics, need not to typecast the object.
List al = new ArrayList(); List<String> al = new ArrayList<String>();
[Link]("hello"); [Link]("hello");
String s = (String) [Link](0); //typecasting String s = [Link](0);

• Compile-Time Checking: It checks at compile time. So, Issues will not raise at run-
time. It is better to handle the problem at compile time than runtime.

List<String> list = new ArrayList<String>();


[Link]("hello");
[Link](32); //Compile Time Error

45
Generic Programming: Type parameters

The type parameters naming conventions:

T - Type
E - Element
K - Key
N - Number
V - Value
46
General Form of a Generic Class
❖Class refers any type is a generic class. T type parameter is used to
create the generic class of specific type.
❖Syntax to Create a generic class:
class class_name<T>{
T obj;
void set(T obj){ ▪ T type indicates any type
[Link]=obj; such as String, Integer, and
} Float.
T get(){ ▪ The type is used to store
return obj; and retrieve the data.
}
} 47
Create object for Generic Class
❖Syntax to Create Object using generic class:
class-name<type-arg-list > var-name = new class-name<type-arg-list>(arg-list);
❖ Example:
Set<Integer> set=new HashSet<Integer>(50);
import [Link].*;
public class Main {
public static void main (String[]args) {
Set < Integer > set = new HashSet < Integer > ();
[Link] (23);
[Link] (12);
Iterator < Integer > it = [Link] ();
int sum = 0;
while ([Link] ())
sum += [Link] ();
[Link] (sum);
}
} 48
Generic Class Example
class Mark < T > { public class Main {
T obj; public static void main (String[]arg) {
Mark (T obj) { Mark < Integer > sem1 = new Mark < Integer > (81);
[Link] = obj; [Link] ("class Mark is of type:" + sem1);
} [Link] ([Link] ());
public T getObj () { Mark < Float > sem2 = new Mark < Float > (15.25f);
return obj; [Link] ("class Mark is of type:" + sem2);
} [Link] ([Link] ());
public void setObj (T obj) { }}
[Link] = obj;
}
public String toString () {
return [Link] ().getName ();
}
}

49
Ex1: Generic Class with Two Type Parameters
import [Link];
import [Link];
public class Main {
public static void main (String[]args) {
Map < Character, Integer > count = new HashMap < Character, Integer > ();
String inp = "OOP in SCOPE";
// Iterating through each character in the input string
for (char c:[Link] ()) {
// If the character is already in the map, increment its count
if ([Link] (c)) {
[Link] (c, [Link] (c) + 1);}
else {
// Otherwise, add the character to the map with a count of 1
[Link] (c, 1);}
}
// Iterating through the entries of the map to print the character counts
for ([Link] entry:[Link] ()) {
[Link] ([Link] () + " occurs " + [Link] ());}
}
}
50
Ex 2: Generic Class with Two Type Parameters
class Student < T, U > {
T rno; public class Main {
U rank; public static void main (String[]arg) {
public Student (T rno, U rank) { Student < String, Integer > s1 = new Student < String, Integer >
[Link] = rno; ("23BCE7010", 2);
[Link] = rank; [Link] (s1);
} Student < Integer, String > s2 = new Student < Integer, String >
public T getRno () { (10005, "10");
return rno; [Link] (s2);
} }}
public void setRno (T rno) {
[Link] = rno;
}
public U getRank () {
return rank;
}
public void setRank (U rank) {
[Link] = rank;
}
public String toString () {
return "Student [rno=" + rno + ", rank=" + rank + "]";
}
}
51
Generic method
• Generic method allows any type of parameters.
• The scope of parameters is only inside the method.
• It allows static and non-static methods

❖Syntax: <type-Parameters> return_type method_name(parameter list)


{
// ..
}

❖Example
< E > void ShowArray(E[] elements)

52
Generic method: Example
public class Main {
public static <E > void ShowArray (E[]elements)
{
for (E s:elements) {
[Link] (s + " ");
}
[Link] ();
}
public static void main (String args[]) {
Integer[]intArray = { 1, 2, 5, 70, 9 };
Character[]chArray = { 'V', 'I', 'T', '-', 'A', 'P' };
[Link] ("Integer Array");
ShowArray (intArray);
[Link] ("Character Array");
ShowArray (chArray);
}
}

53
Generic Interface
❑ Generic interface allows any type of parameters.

❖Syntax: interface GenInterface <T> {


T compute(T t);
}
class className<T> implements interfaceName<T> {
// ....
}

❖Example interface GenInterface <T>


{
void move(T t, String Code);
T show();
String print();
}
54
Generic Interface: Example 1
interface GenInterface {
void move(Object t, String Code);
Object show();
String print(); }

public class Main implements GenInterface {


private String l;
private Object item;
public void move (Object t, String Code) {
item = t;
l = Code;
[Link] ("item: " + t + " Word: " + l); }
public Object show () {
return item;
}
public String print () {
return l;
}
public static void main (String[]args) {
Main a = new Main ();
[Link] ();
[Link] ();
[Link] (56, "Hi"); }} 55
Generic Interface: Example 2
public class Main implements GenInterface {
private Object l;
private Object item;
public void move (Object t, Object Code) {
item = t;
interface GenInterface < T > { l = Code;
void move (T t, T Code); [Link] ("item: " + t + " Value: " + l);
T show (); }
T print (); public Object show () {
} return item;
}
public Object print () {
return l;
}
public static void main (String[]args) {
Main a = new Main ();
[Link] ();
[Link] ();
[Link] (56, "Hi");
[Link] ("Welcome", 123);
}
}
56
Generic Constructor: Example
class GenCons {
private double val;
<T extends Number > GenCons (T arg) {
val = [Link] ();
}
void show () {
[Link] ("val: " + val);
}
}

class Main {
public static void main (String args[]) {
GenCons test = new GenCons (555);
GenCons test2 = new GenCons (15.25F);
[Link] ();
[Link] ();
}
}

57
Java Generics: Wildcard
• Wildcard is an approach in Generic Programming.

• The ? (question mark) symbol denotes the wildcard. It means unknown (any) type.

• Wildcard can be used as a type of a parameter, field, return type, or local variable.

• However, wildcard is not allowed to use a as a type argument for a generic method
invocation, a generic class instance creation, or a supertype.

• The wildcard is used to remove the incompatibility between different instantiations of a


generic type. It is done by using wildcards ? as an actual type parameter

58
Wildcard Types
Types of wildcards in Java:
• Upper bounded wildcards,
• Lower Bounded Wildcards, and
• Unbounded Wildcards.

Bounded Types:
• A bounded wildcard states the type argument can be an
upper bound, lower bound, and unbounded.
• It restricts the types of objects which are using in a method.
59
Wildcard: Upper bounded
• The most widely used wildcard is the upper bound.
• Create an upper bound that declares the superclass to specify Type parameter, from which all type
arguments must be derived.
• Upper bounded wildcards decrease the restrictions on a variable.
• It restricts the unknown type to be a specific type or a subtype of that type.
• It is declared with Type variable (wildcard character "?") followed by the extends (in case of, class)
or implements (in case of, interface) keyword, followed by its upper bound.

Syntax:
<T extends superclass>
• T can only be replaced by superclass, or subclasses of superclass.
• Thus, superclass defines upper limit. 60
Wildcard: Upper bounded
• Example: <? extends Number>
• Number class has subclasses like Integer, Float,
import [Link];
double. class Sample <T extends Number> {
// array of Number or subclass
• So, user can call the method of Number class T[] nums;
Sample(T[] obj) {
through any child class object. nums = obj;
}
<Number>
T sum(){
• Works with only class Number, not with its // returns Type parameter
return T;
subclasses. }

• So, <? extends Number> is less


restrictive than <Number>.
61
Upper bounded: Example
import [Link];
import [Link];
public class Upperbound {
// Method to calculate the sum of a list of numbers
private static Double add(ArrayList<? extends Number> num) {
double sum = 0.0;
// Iterate through the list and sum the elements
for (Number n : num) {
sum = sum + [Link](); }
return sum; }
public static void main(String[] args) {
// Create a list of integers and add elements
List<Integer> x = new ArrayList<Integer>();
[Link](10);
[Link](20);
// Display the sum of the integer list
// Explicit conversion to ArrayList
[Link]("Displaying the sum= " + add(new ArrayList<>(x)));

// Create a list of doubles and add elements


List<Double> y = new ArrayList<Double>();
[Link](30.0);
[Link](40.0);
// Display the sum of the double list
// Explicit conversion to ArrayList
[Link]("Displaying the sum= " + add(new ArrayList<>(y))); }} 62
Wildcard: Lower bounded
• Lower bounded wildcards restricts the unknown type to be a specific type or a supertype of that type.
• It is declaring with wildcard ("?") followed by the super keyword, followed by its lower bound

Syntax:
<? super subclass>
Example:
<? super Integer>

• Integer, is a wrapper class.


• <? super Integer> works with type Integer or any of its superclasses.
• But <Integer> works with type Integer only.
• Hence, <? super Integer> is less restrictive than <Integer>.
63
Lower bounded: Example
import [Link];
import [Link];
public class Lowerbound {
public static void print (List < ? super Integer > list) {
for (Object n : list)
{
[Link] (n);
}
}
public static void main (String[]args) {
List < Integer > x = [Link] (5, 10, 15);
[Link] ("Integer values");
print (x);
List < Number > y = [Link] (10.0, 25.0, 35.0);
[Link] ("Number values");
print (y);
}
}

64
Wildcard: UnBounded
• The unbounded wildcard 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 the functionality provided in the Object class.
• When code inside the methods not depend on the type parameter.

public class Unbounded {


public static void display(List <?> list) {
for(Object o:list) {
[Link](o);
}
}

65
Unbounded: Example
import [Link];
import [Link];
public class Unbounded {
// Generic method to display elements of a list
public static <T> void display(List<T> list) {
for (T element : list) {
[Link](element);
}
}
public static void main(String[] args) {
// Create a list of integers and display its elements
List<Integer> x = [Link](1, 2, 3);
[Link]("Integer values");
display(x);
// Create a list of strings and display its elements
List<String> y = [Link]("One", "Two", "Three");
[Link]("String values");
display(y);
}
} 66
Wildcard in Java Generics Example 2
import [Link].*;
abstract class Shape {
abstract void area ();
}
class Rectangle extends Shape {
void area () {
[Link] ("Area of rectangle");
}
}
class Square extends Shape {
void area () {
[Link] ("Area of square");
}
}
class Main {
//method accepts only child class of Shape
public static void areaShapes (List < ? extends Shape > lists) {
for (Shape s : lists) {
[Link] ();
}
}
public static void main (String args[]) {
List < Rectangle > list1 = new ArrayList < Rectangle > ();
[Link] (new Rectangle ());
List < Square > list2 = new ArrayList < Square > ();
[Link] (new Square ());
areaShapes (list1);
areaShapes (list2);
}}
67
Generics example
import [Link].*;
class GenType
abstract class<Shape
T > {{
private
abstractTvoid
t; area ();
} public T get () {
return
class this.t; extends Shape {
Rectangle
}
void area () {
public void set
[Link] (T t1) {
("Area of rectangle");
this.t
} = t1;
} }
}
class Square extends Shape {
public class()
void area Main{ {
public static <T > boolean
[Link] ("AreaisEqual (GenType < T > g1, GenType < T > g2)
of square"); {
return
} [Link] ().equals ([Link] ());
} }
public
class static
Main { <T extends Comparable < T >> int compare (T t1, T t2) {
return [Link]
//method accepts only (t2);
child class of Shape
}
public static void areaShapes (List < ? extends Shape > lists) {
public static void
for (Shape s : lists) main (String
{ args[]) {
GenType < String
[Link] (); > g1 = new GenType <> ();
[Link]
} ("Hi");
GenType
} < String > g2 = new GenType <> ();
[Link] ("Hi");
public static void main (String args[]) {
boolean
List <isEqual
Rectangle = Main.
> list1< String
= new > isEqual (g1,
ArrayList g2);
< Rectangle > ();
[Link] (isEqual);
[Link] (new Rectangle ());
//above
Liststatement
< Square > can be written
list2 simply as< Square > ();
= new ArrayList
isEqual = [Link]
[Link] (new Square(g1, ());g2);
[Link]
areaShapes (list1); (isEqual);
[Link]
areaShapes (list2); ([Link] ("abc", "abc"));
}}}
} 68
End of Module 5

69

You might also like