一个泛型类
package com.zhao.generate; /** * 定义泛型类 <T>不能是基本类型 * 编写泛型时,需要定义泛型类型<T>; * 静态方法不能引用泛型类型<T>,必须定义其他类型(例如<K>)来实现静态泛型方法 * @param <T> */ public class Genericity<T> { public static void main(String[] args) { System.out.println(new Genericity<String>("100", "10").toString()); System.out.println(Genericity.create("12", "红绒花").toString()); } private T first; private T last; public Genericity(T first, T last) { this.first = first; this.last = last; } public String toString() { return "Genericity{" + "first=" + first + ", last=" + last + '}'; } // 静态泛型方法应该使用其他类型区分: public static <K> Genericity<K> create(K first, K last) { return new Genericity<K>(first, last); } public T getFirst() { return first; } public void setFirst(T first) { this.first = first; } public T getLast() { return last; } public void setLast(T last) { this.last = last; } }
多个泛型类
package com.zhao.generate; /** * 定义多个泛型类 * 泛型可以同时定义多种类型,例如Map<K, V>。 * @param <K> * @param <T> */ public class Genericity1<K,T> { public static void main(String[] args) { Genericity1<String, Integer> g = new Genericity1<>("USER",12); System.out.println(g.toString()); } private K first; private T last; public Genericity1(K first, T last) { this.first = first; this.last = last; } @Override public String toString() { return "Genericity1{" + "first=" + first + ", last=" + last + '}'; } public K getFirst() { return first; } public void setFirst(K first) { this.first = first; } public T getLast() { return last; } public void setLast(T last) { this.last = last; } }