Java Generics Introduction

//Java Generics Introduction
  • Generics in Java is one of important feature added in Java 5.
  • Enables types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Type parameters provide a way for you to re-use the same code with different inputs.
  • Benefits are – 1. Stronger type checks at compile time. 2. Resolves type casting problems. 3. Enabling programmers to implement generic algorithms.

Case(i) : Understanding type checks at compile time (Type Safe) :

Type checking at compile time in Arrays.

  • Arrays are always type safe, there is always  a guarantee that array can hold a particular type of objects.
  • For example if our programming requirement is to hold String type of objects it is recommended to use String array. In the case of string array we can add only string type of objects by mistake if we are trying to add any other type we will get compile time error.
  • Error is- Type mismatch: cannot convert from Integer to String

Type checking at compile time in Collections.

  • Collections are not type safe (if we are not using Generics).
  • For example if our programming requirement is to hold only String objects by mistake if we add any other type we wont get any compile time error, but there may be chance of failing the program at runtime.

Case(ii) : Understanding type casting issues in Collections  :

Type Casting while retrieving elements from Arrays .

  • In the case of arrays at the time of retrieval it is not required to perform any type casting.

Type Casting while retrieving elements from Collection.

  • In the case of collection at the time of retrieval compulsory we should perform type casting otherwise we will get compile time error.

How Generics resolves type casting and provides type safety?

  • To overcome the above problems of collections(type-safety, type casting) generics introduced in java 1.5v . Main objectives of generics are: 1)  To provide type safety to the collections. 2)  To resolve type casting problems.
  • To hold only string type of objects we can create a generic version of ArrayList as follows.

  • For this ArrayList we can add only string type of objects, by mistake if we are trying to add any other type we will get compile time error that is through generics we are getting type safety.
  • At the time of retrieval it is not required to perform any type casting we can assign elements directly to string type variables.
2017-08-31T12:41:51+00:00Categories: core java|Tags: , , |0 Comments

Leave A Comment