0% found this document useful (0 votes)
2 views4 pages

generics2 (1)

Java Generics allow the creation of classes and methods that can operate on different data types using parameterized types, similar to C++ templates. They provide type safety by performing type checks at compile time, and are commonly used in Java's collections framework. The document explains the implementation of generic classes, methods, and bounded type parameters, illustrating their usage with examples.

Uploaded by

anuja.it
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
2 views4 pages

generics2 (1)

Java Generics allow the creation of classes and methods that can operate on different data types using parameterized types, similar to C++ templates. They provide type safety by performing type checks at compile time, and are commonly used in Java's collections framework. The document explains the implementation of generic classes, methods, and bounded type parameters, illustrating their usage with examples.

Uploaded by

anuja.it
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 4

How Do Generics Work In Java?

If you have worked with C++ before, then Java Generics is the same as templates in C+
+. Java Generics allow you to include a parameter in your class/method definition which
will have the value of a primitive data type.

For Example, you can have a Generic class “Array” as follows:


Class Array<T> {….}

Where <T> is the parameterized type.

Next, you can create objects for this class as follows:

Array int_array<Integer> = new Array<Integer> ()


Array<Character> char_array = new Array<Character> ();
So given a Generic parameterized class, you can create objects of the same class with
different data types as parameters. This is the main essence of using Java Generics.

Similarly, you can write a generic method with a parameterized type for sorting an array
and then instantiate this method to any primitive type.

Java Generics are mostly used with the collections framework of Java. The different
collections like LinkedList, List, Map, HashMap, etc. use Generics for implementation.
Generics provide type-safety as the type checking is done at compile time thus making
your code more stable.

Let us now more into the details of Generic classes and methods as well as other related
topics.

Generic Classes
A Generic class is the same as a normal class except that the classname is followed by
a type in angular brackets.

A general definition of a Generic class is as follows:

class class_name<T>
{
class variables;
…..
class methods;
}
Once the class is defined, you can create objects of any data type that you want
as follows:
class_name <T> obj = new class_name <T> ();
For Example, for Integer object the declaration will be:
class_name <Integer> obj = new class_name<Integer>;
Similarly, for the String data type, the object will be:
class_name <String> str_Obj = new class_name<String>;
An example implementation for the Generic class is shown below.
class MyGenericClass<T>
{
T obj;
void add(T obj)
{
this.obj=obj;
}
T get()
{
return obj;
}
}

class Main
{
public static void main(String args[])
{
MyGenericClass<Integer> m_int=new MyGenericClass<Integer>();
m_int.add(2);
MyGenericClass<String>mstr=new MyGenericClass<String>();
mstr.add("SoftwaretestingHelp");

System.out.println("Member of MyGenericClass<Integer>:" + m_int.get());


System.out.println("Member of MyGenericClass<String>:" + mstr.get());
}
}
Output:

In the above program, a class MyGenericClass is a generic class. It has two methods
i.e. add and get. The method add initializes the generic object while the get methods
return the object.

In the main function, we declare two objects of Integer and String type each. We initialize
both these objects with their respective initial values using the add method and then
output the contents of these objects using the get method.

We presented the Generic class example above with one type parameter. But in reality,
a class can have more than one type parameter as well. In this case, the type
parameters are separated by a comma.

The following example demonstrates this:


classTest_Generics<T1, T2>
{
T1 obj1; // An object of type T1
T2 obj2; // An object of type T2

// constructor to initialise T1 & T2 objects


Test_Generics(T1 obj1, T2 obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

public void print()


{
System.out.println("T1 Object:" + obj1);
System.out.println("T2 Object:" + obj2);
}
}

class Main
{
public static void main (String[] args)
{
Test_Generics<String, Integer>obj =
newTest_Generics<String, Integer>("Java Generics", 1);

obj.print();
}
}
Output:

In this program, we have two type parameters i.e. T1 and T2. We have functions to
initialize the member objects and also to print the contents. In the main function, we
declare an object with two types i.e. String and Integer. The output of the program shows
the contents of the created object.

Just like classes, you can also have Generic interfaces. We will learn all about interfaces
in a separate topic.

Java Generic Methods


Just as you can have Generic classes and interfaces, you can also have Generic
methods in case you do not need an entire class to be Generic.

The following program shows the implementation of the Generic method


“printGenericArray”. Note the method call in the main function. Here we make two calls
to the Generic method, first time with <Integer> type and then with <String> type.

public class Main{


public static < T > void printGenericArray(T[] items) {
for ( T item : items){
System.out.print(item + " ");
}
System.out.println();
}
public static void main( String args[] )
{
Integer[] int_Array = { 1, 3, 5, 7, 9, 11 };
Character[] char_Array = { 'J', 'A', 'V', 'A', 'T','U','T','O','R','I','A', 'L',

System.out.println( "Integer Array contents:" );


printGenericArray(int_Array );

System.out.println( "Character Array contents:" );


printGenericArray(char_Array );
}
}
Output:

Bounded Type Parameters


Bounded Type Parameters come into picture when you want to limit the data types in
Generics. For Example, if you want that a particular generic class or method or any
interface that should work only for numeric data types, then you can specify that using
the “extends” keyword.
This is shown below:
List<? extends Number> myList = new ArrayList<Long>();
List<? extends Number> list1 = new ArrayList<Integer>();
The above two declarations will be accepted by the compiler as Long and Integer are
subclasses of Number.

The next declaration, however, is going to be a problem.

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


This will give a compile-time error because String is not a Number. The symbol ‘?’ in the
above example is known as a wildcard and we will discuss it next.

So in general, bounded type parameters are mostly used when you want to restrict the
data types to be used in your generics code.

You might also like