Generics (Cont.)
Generic Functions
We can also write generic functions that can be called with different types of arguments based on the type of arguments passed to generic method.
The compiler handles each method.
Advantages of Generics
Programs that uses generics have many benefits over non-generic code:
- Code reuse:
We can write a method/class/interface once and use for any type we want.
- 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 stores names of students, and if by mistake, programmer adds an Integer
object instead of String
, compiler will allow it.
But, when we retrieve this data from ArrayList
, it causes problems at run time.
The compiler handles each method.
When we were kids, we used to be afraid of the dark.
But when we grew up, the electricity bill made us afraid of the light!
|