泛型类可以有多个类型参数。以下示例将展示上述概念。
使用您喜欢的编辑器创建以下java程序,并保存到文件:MultipleTypeParameters.java 中,代码如下所示 -
package com.zyiz; public class MultipleTypeParameters { public static void main(String[] args) { Box3<Integer, String> box = new Box3<Integer, String>(); box.add(Integer.valueOf(103), "Hello World"); System.out.printf("Integer Value :%d\n", box.getFirst()); System.out.printf("String Value :%s\n", box.getSecond()); Box3<String, String> box1 = new Box3<String, String>(); box1.add("Message", "Hello World"); System.out.printf("String Value :%s\n", box1.getFirst()); System.out.printf("String Value :%s\n", box1.getSecond()); } } class Box3<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; } }
执行上面代码,得到以下结果 -
Integer Value :103 String Value :Hello World String Value :Message String Value :Hello World