- 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
Can you create an array of Generics type in Java?
Generics is a concept in Java where you can enable a class, interface and, method, accept all (reference) types as parameters. In other words it is the concept which enables the users to choose the reference type that a method, constructor of a class accepts, dynamically. By defining a class as generic you are making it type-safe i.e. it can act up on any datatype.
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
Array of generic types
No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.
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>[5]; } }
Compile time error
GenericsExample.java:12: error: generic array creation Student<Float>[] std1 = new Student<Float>[5]; ^ 1 error
- Related Articles
- How can we restrict Generics (type parameter) to sub classes of a particular class in Java?
- Can you assign an Array of 100 elements to an array of 10 elements in Java?
- Generics in Java
- Can you pass the negative number as an Array size in Java?
- Get the Component Type of an Array Object in Java
- Can you change size of Array in Java once created?
- How to create an array of Object in Java
- How to create an Array in Java?
- Can we create an object of an abstract class in Java?
- Is an array a primitive type or an object in Java?
- How to create an array of linked lists in java?
- Create an object array from elements of LinkedList in Java
- Create Ennead Tuple from an array in Java
- Create KeyValue Tuple from an array in Java
- Create Decade Tuple from an array in Java

Advertisements