泛型类可以具有参数化类型,其中类型参数可以替换为参数化类型。以下示例将展示上述概念。
package com.learnfk; 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; } }
这将产生以下输出。
Integer Value :10 String Value :[Hi, Hello, Bye]
参考链接
https://www.learnfk.com/java-generics/java-generics-parameterized-types.html
标签:box,Java,messages,无涯,Value,add,泛型,java,public From: https://blog.51cto.com/u_14033984/9004472