
- Generics - Home
- Generics - Overview
- Generics - Environment Setup
- Examples - Generic Classes
- Generics - Generic Classes
- Type Parameter Naming Conventions
- Generics - Type inference
- Generics - Generic Methods
- Generics - Multiple Type Parameters
- Generics - Parameterized Types
- Generics - Raw Types
- Examples - Bounded Type Parameters
- Bounded Type Parameters
- Generics - Multiple Bounds
- Examples - Collections
- Generics - Generic List
- Generics - Generic Set
- Generics - Generic Map
- Examples - Wild Cards
- Upper Bounded Wildcards
- Generics - Unbounded Wildcards
- Lower Bounded Wildcards
- Generics - Guidelines for Wildcards
- Type Erasure
- Generics - Generic Types Erasure
- Generics - Bound Types Erasure
- Unbounded Types Erasure
- Generics - Generic Methods Erasure
- Restrictions on Generics
- Generics - No Primitive Types
- Generics - No Instance
- Generics - No Static field
- Generics - No Cast
- Generics - No instanceOf
- Generics - No Array
- Generics - No Exception
- Generics - No Overload
- Generics Useful Resources
- Generics - Quick Guide
- Generics - Useful Resources
- Generics - Discussion
Java Generics - Parameterized Types
A Generic class can have parameterized types where a type parameter can be substituted with a parameterized type. Following example will showcase above mentioned concept.
Example
Create the following java program using any editor of your choice.
GenericsTester.java
package com.tutorialspoint; import java.util.ArrayList; import java.util.List; public class GenericsTester { public static void main(String[] args) { Box<Integer, List<String>> box = new Box<Integer, List<String>>(); List<String> messages = new ArrayList<String>(); messages.add("Hi"); messages.add("Hello"); messages.add("Bye"); box.add(Integer.valueOf(10),messages); System.out.printf("Integer Value :%d\n", box.getFirst()); System.out.printf("String Value :%s\n", box.getSecond()); } } class Box<T, S> { private T t; private S s; public void add(T t, S s) { this.t = t; this.s = s; } public T getFirst() { return t; } public S getSecond() { return s; } }
This will produce the following result.
Output
Integer Value :10 String Value :[Hi, Hello, Bye]
Advertisements