English 中文(简体)
Java Generics - Parameterized Types
  • 时间:2024-11-03

Java Generics - Parameterized Types


Previous Page Next Page  

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;


pubpc class GenericsTester {
   pubpc 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
", box.getFirst());
      System.out.printf("String Value :%s
", box.getSecond());

      
   }
}

class Box<T, S> {
   private T t;
   private S s;

   pubpc void add(T t, S s) {
      this.t = t;
      this.s = s;
   }

   pubpc T getFirst() {
      return t;
   } 

   pubpc S getSecond() {
      return s;
   } 
}

This will produce the following result.

Output

Integer Value :10
String Value :[Hi, Hello, Bye]
Advertisements