2. Generics
⢠Generics means parameterized data types.
⢠The idea is to allow data 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.
3. generics
⢠JDK 5 introduces generics, which
supports abstraction over
types (or parameterized types) on classes and
methods.
⢠The class or method designers can be generic
about types in the definition, while the users are
to provide the specific types (actual type) during
the object instantiation or method invocation.
4. ⢠The primary usage of generics is to abstract over
types for the Collection Framework.
⢠Auto-Boxing/Unboxing between Primitives and
their Wrapper Objects
5. Generics
⢠Generics helps to create classes, interfaces, and
methods that can be used with different types of
objects (data). Hence, allows us to reuse our
code.
⢠Note: Generics does not work with primitive
types (int, float, char, etc).
⢠Generics is used in Java, we can use the ArrayList
class of the Java collections framework.
⢠ArrayList class is an example of a generics class.
We can use ArrayList to store data of any type.
6. Generic Programming
⢠Generics helps to create classes, interfaces,
and methods that can be used with different
data types of objects (data). Hence, allows us
to reuse our code.
⢠Note: Generics does not work with primitive
types (int, float, char, etc).
7. Advantages
⢠Type-safety : We can hold only a single type of
objects in generics. It doesnât allow to store other
objects.
⢠Type casting is not required: There is no need to
typecast the object.
⢠Compile-Time Checking: It is checked at compile
time so problem will not occur at runtime. The
good programming strategy says it is far better to
handle the problem at compile time than
runtime.
8. Types of Java Generics
⢠Generic Type Class
⢠Generic Interface
⢠Generic Method
⢠Generic Constructor
9. Syntax for generics
Class classname <data_type_variable>
{ }
Generic class:
Generic method:
class Demo
{
<data_type_ variable> return_ data _type method_name ()
{
}
}
10. Generic Class
⢠A class is said to be Generic if it declares one or
more type variables. These variable types are
known as the type parameters of the Java Class.
⢠we use <> to specify parameter types in generic
class creation.
⢠Generics Work Only with Objects
11. Syntax for creating an Object of a Generic type
Class_name <data type> reference_name = new
Class_name<data type> ();
(OR)
Class_name <data type> reference_name = new
Class_name<>();
Generic Class
12. example
class Test<T>
{ T a;
T b;
Test(T x, T y)
{
a=x;
b=y;
}
}
public class Main
{
public static void main(String[] args) {
Test<Integer> obj=new Test<Integer>(2,3);
System.out.println(obj.a+obj.b);
}
}
13. //addition of two numbers using generic class
class Test <T>
{ T a;
T b;
//generic cons....
Test(T x, T y)
{
a=x;
b=y;
}
//generic method
T get()
{
return a;
}
}
class Main {
public static void main(String[] args) {
Test<Integer> obj = new Test<Integer>(34,23);
System.out.println(obj.a+obj.b);
System.out.println(obj.get());
Test<Float> obj1 = new Test<Float>(34.1f,23.3f);
System.out.println(obj1.a+obj1.b);
System.out.println(obj1.get());
}
}
14. class Main {
public static void main(String[] args) {
// initialize generic class with Integer data
GenericsClass<Integer> intObj = new GenericsClass<>(5);
System.out.println("Generic Class returns: " + intObj.getData());
// initialize generic class with String data
GenericsClass<String> stringObj = new GenericsClass<>("Java Programming");
System.out.println("Generic Class returns: " + stringObj.getData());
}
} class GenericsClass<T> {
// variable of T type
private T data;
public GenericsClass(T data) {
this.data = data;
}
// method that return T type variable
public T getData() {
return this.data;
}
}
Output
Generic Class returns: 5
Generic Class returns:
Java Programing
15. ⢠T indicates the type parameter. Inside the
Main class, we have created objects of
GenericsClass named intObj and stringObj.
⢠While creating intObj, the type parameter T is
replaced by Integer. This means intObj uses
the GenericsClass to work with integer data.
⢠While creating stringObj, the type parameter T
is replaced by String. This means stringObj
uses the GenericsClass to work with string
data.
16. Generics Methods Rules
⢠In passing arguments into methods, You place the arguments inside
the round bracket () and pass them into the method.
⢠In generics, instead of passing arguments, we pass type
information inside the angle brackets <>.
⢠All generic method declarations have a data type parameter section
by angle parameter
Example: <E>
⢠Each type parameter section contains one or more type parameters
separated by commas
⢠Example: <E1,T> void disp(E1 a, T b)
Syntax:
<type-parameter> return_type method_name (parameters) {...}
17. 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', 'T','P','O','I','N','T' };
System.out.println( "Printing Integer Array" );
printArray( intArray );
System.out.println( "Printing Character Array" );
printArray( charArray );
}
}
18. For-each Loop
Syntax:
for(data_type variable : array | collection)
{
//body of for-each loop
}
Example:
class ForEachExample1{
public static void main(String args[]){
//declaring an array
int arr[]={12,13,14,44};
//traversing the array with for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
19. Generics Methods
class Main {
public static void main(String[] args) {
// initialize the class with Integer data
DemoClass demo = new DemoClass();
demo.<String>genericsMethod("Java Programming");
}
}
class DemoClass {
// generics method
public <T> void genericsMethod(T data) {
System.out.println("This is a generics method.");
System.out.println("The data passed to method is " + data);
}
}
20. ⢠public <T> void genericMethod(T data) {...} Here,
the type parameter <T> is inserted after the
modifier (public) and before the return type
(void).
⢠We can call the generics method by placing the
actual type <String> inside the bracket before the
method name.
⢠demo.<String>genericMethod("Java
Programming"); Note: In most cases, we can omit
the type parameter while calling the generics
method. It is because the compiler can match the
type parameter using the value passed to the
method. For example,
⢠demo.genericsMethod("Java Programming");
21. Generic Constructor
class sample
{
Object a;
<T> sample(T b)
{
a=b;
}
void disp(){
System.out.println(a);
}
}
public class Generic1 {
public static void main(String ar[]){
sample s=new sample(âHi");
sample s=new sample(âAâ);
sample s=new sample(4);
sample s=new sample(5.4);
s.disp();
}
}
22. Generic Constructor
class sample
{
<T> sample(T x,T y)
{
System.out.println(x);
System.out.println(y);
}
}
public class Generic2 {
public static void main(String ar[]){
sample s=new sample(2,4);
}
}
Generic Type with more than one parameter
23. public class Generic4 {
<E,T> void disp(E a, T b){
System.out.println(a);
System.out.println(b);
}
public static void main(String ar[]){
Generic4 g=new Generic4();
g.disp(4,6.5);
g.disp(4.5,5);
}
}
Generic Method
24. Generic Method
class sample{
< E > void printArray(E[] elements) {
for ( E element : elements){
System.out.println(element );
}
}
}
public class Generic3{
public static void main( String args[] ) {
sample s=new sample();
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { 'E', 'N', 'G', 'I', 'N','E','E','R','I','N','G' };
System.out.println( "Printing Integer Array" );
s.printArray(intArray);
System.out.println( "Printing Character Array" );
s.printArray(charArray);
}
}
25. class sample<G>
{
G obj;
sample(G a){
obj=a;
}
void disp(){
System.out.println(obj);
}
}
public class Generic7{
public static void main(String ar[]){
sample <Integer> s=new sample<Integer>(15);
s.disp();
sample <String> s1=new sample<String>(âFox");
s1.disp();
}
Generic Class
26. class sample<G, T>{
G obj1;
T obj2;
sample(G a, T b){
obj1=a;
obj2=b;
}
void disp(){
System.out.println(obj1+" "+obj2);
}
}
public class Generic8{
public static void main(String ar[]){
sample <Integer, String> s=new sample<Integer, String> (15,âKongu");
s.disp();
sample <String,Integer> s1=new sample<String,Integer>(âKongu
eng",20);
s1.disp();
Generic Class
27. class twogen<T,V>{
T obj1;
V obj2;
twogen(T o1,V o2) {
obj1=o1;
obj2=o2;
}
T getobj1() {
return obj1;
}
V getobj2() {
return obj2;
}
void showType() {
System.out.println("type is" + obj1.getClass().getName());
System.out.println("type is" + obj2.getClass().getName());
}}
public class Generic11{
public static void main(String args[]) {
twogen<Integer,String> tobj=new twogen<Integer,String>(99,"kec");
tobj.showType();
int v=tobj.getobj1();
String u=tobj.getobj2();
System.out.println("u="+u+" "+"v="+v);
}}
Generic Class
Ans:
type isjava.lang.Integer
type isjava.lang.String
u=kec v=99
28. class constructors{
<T extends Number>int showval(T a, T b){
return (a.intValue()+b.intValue());
}}
class Generic15{
public static void main(String r[]){
constructors s=new constructors();
int sum=s.showval(10,20);
System.out.println(sum);
}}
Generic Type addition
29. class constructors{
int a;
<T extends Number>constructors(T x){
a=x.intValue();
}
void showval(int b){
int sum=a+b;
System.out.println("sum:"+sum);
}}
class Generic14{
public static void main(String r[]){
constructors s1=new constructors(10);
constructors s2=new constructors(12.3F);
s1.showval(9);
s2.showval(10);
}}
Generic Type
addition
30. class sample
{
static <T extends Number>
void add (T a, T b)
{
System.out.println(b.doubleValue()+a.doubleValue());
}
public static void main(String aa[])
{
Integer a=8, b=10;
add(a,b);
Float c=12.5f,d=45.5f;
add(c,d);
Double e=12.5,f=45.5;
add(e,f);
}}
Generic Type addition
31. Generic Interface
interface I1<T>
{
void disp(T a);
}
class sample <T>implements I1<T>
{
public void disp(T a)
{
System.out.println(a);
}}
public class Generic5 {
public static void main(String ar[])
{
sample <Integer>s=new sample<Integer>();
s.disp(5);
sample <Double>s1=new sample<Double>();
s1.disp(5.4);
If we using 2 parameter in the
inherited class
class sam <T,U> implements I1<T>
32. class sample1<T>{
void disp(T a){
System.out.println(a);
}
}
class sample2<T> extends sample1<T>{
void disp(T a){
System.out.println("Derived"+a);
}
}
public class Generic10 {
public static void main(String ar[]){
sample1<Integer> s1=new sample1<Integer>();
s1.disp(4);
sample1<Double> s2=new sample2<Double>();
s2.disp(5.2);
}
}
33. class general{
int num;
general(int i){
num=i;
}
int get(){
return num;
}}
class Gen<T>extends general{
T obj;
Gen(T o,int i){
super(i);
obj=o;
}
T getobj(){
return obj;
}
void show(){
System.out.println("base class...");
}}
Generic Class Hierarchies
ContdâŚ
34. class gen2<T,V> extends Gen<T>{
V obj1;
gen2(T o, V s,int i){
super(o,i);
obj1=s;
}
V getobj2(){
return obj1;
}
void show(){
super.show();
System.out.println("subclass...");
}}
public class Generic16{
public static void main(String r[]) {
gen2<Integer,String> is=new gen2<Integer,String>(100,"java",100);
System.out.println("String:"+is.getobj2());
System.out.println("value:"+is.getobj());
System.out.println("nongeneric value:"+is.get());
is.show();
}}
Generic Class Hierarchies
35. Wildcards 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.
36. Wildcards in Java
⢠The question mark (?) is known as the wildcard
in generic programming .
⢠It represents an unknown type.
⢠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.
37. class Gen<T>{
T obj;
Gen(T o) {
obj=o;
}
T getobj() {
return obj;
}}
class rawtype{
public static void main(String r[]){
Gen<Integer>o1=new Gen<Integer>(100);
Gen<String>o2=new Gen<String>("java");
//int v=o1.getobj();
System.out.println("Value:"+o1.getobj());
//String s=o2.getobj();
System.out.println("String:"+o2.getobj());
Gen raw=new Gen(new Double(100.0));
double d=(Double)raw.getobj();
System.out.println("raw value:"+d);