- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is need of introducing Generics, when Arrays already present in Java?
Arrays in Java are used to store homogeneous datatypes, where generics allow users to dynamically choose the type (class) that a method, constructor of a class accepts, dynamically.
By defining a class generic you are making it type-safe i.e. it can act up on any datatype. To understand generics let us consider an example −
Example
class Student<T>{ T age; Student(T age){ this.age = age; } public void display() { System.out.println("Value of age: "+this.age); } } public class GenericsExample { public static void main(String args[]) { Student<Float> std1 = new Student<Float>(25.5f); std1.display(); Student<String> std2 = new Student<String>("25"); std2.display(); Student<Integer> std3 = new Student<Integer>(25); std3.display(); } }
Output
Value of age: 25.5 Value of age: 25 Value of age: 25
Why do we need generics
Usage of generics in your code you will have the following advantages −
Type check at compile time − usually, when you use types (regular objects), when you pass an incorrect object as a parameter, it will prompt an error at the run time.
Whereas, when you use generics the error will be at the compile time which is easy to solve.
Code reuse − You can write a method or, Class or, interface using generic type once and you can use this code multiple times with various parameters.
For certain types, with formal types, you need to cast the object and use. Using generics (in most cases) you can directly pass the object of required type without relying on casting.
- Related Articles
- Why do we need generics in Java?
- What is Java Generics?
- Generics in Java
- What are raw types in generics in Java?
- What are wildcards arguments in Generics In Java?
- What is length in Java Arrays?
- What is the need of wrapper classes in Java?
- What are Unbounded wildcard w.r.t Generics method in Java?
- Bounded-types in generics in Java?
- What are upper-bounded wildcard w.r.t Generics method in Java?
- What are lower-bounded wildcard w.r.t Generics method in Java?
- Templates in C++ vs Generics in Java
- Bounded types with generics in Java\n
- Generics vs non-generics in C#
- Can you create an array of Generics type in Java?
