有许多缘由促成了泛型的出现,而最引人注意的一个缘由,就是为了建立容器类。java
/** * 泛型类 */ public class Store<T> { T value; public Store(T value) { this.value = value; } static public void main(String[] args) { Store<String> store = new Store<String>("DARKGEM"); System.out.println(store.getValue()); } public T getValue() { return value; } public void setValue(T value) { this.value = value; } }
public class App { public static void main(String[] args) { Store<String> store = new Store<String>() { String val; public String get() { return val; } public void set(String val) { this.val = val; } }; store.set("DARKGEM"); System.out.println(store.get()); } /** * 泛型接口 */ public interface Store<T> { T get(); void set(T val); } }
public class App { /** * 泛型方法 */ static <T> String transform(T val) { return String.valueOf(val); } static public void main(String[] args) { System.out.println("AAA"); } }
import java.util.LinkedList; import java.util.List; public class App { public static void main(String[] args) { //compile pass Abs abs = new Impl(); //compile fail List<Abs> fail = new LinkedList<Impl>(); //compile pass List<? extends Abs> pass = new LinkedList<Impl>(); } /** * 抽象 */ static abstract class Abs { } /** * 实际 */ static class Impl extends Abs { } }
经过 <? extends Abs>
能够实现父抽象类容器
引用子实现类容器
这种状况。segmentfault
泛型的概念是针对编译器
的,在编译处理后,泛型信息均可以被去除,而后使用Object代替
,由于Object是全部对象的Root。this
泛型在必定程度上,能够美化咱们的code,在编译时就能够肯定一些错误。可是也不要滥用
泛型特性。code