泛型的主要目的:
就是用来指定容器要持有什么对象,由编译器来确保类型的正确性。
类型参数:
我们可以通过使用类型参数,暂时不指定容器的类型,然后稍后再去决定要去使用什么类型
package com.package15;public class Holder3<T> {private T t;Holder3(T t){this.t=t;}public void setT(T t) {this.t = t;}public T getT() {return t;}public static void main(String[] args) {Holder3<Automobile> h3 = new Holder3<Automobile>(new Automobile());Automobile t = h3.getT();//不需要强制类型转换//h3.setT("aaaaaa");//这个时候制定了类型是Automobile类型//h3.setT(1);h3.setT(new Automobile());}}
T就是类型参数,我们看看到我们在创建Holder3的对象的时候指明了容器的类型是Automobile类型。所以此时的set方法中也只能传入Automobile类型的对象;所以17、18行代码会 报错
元组:通过元组我们可以将一组对象打包放在一个单一对象中去。
package com.package15;public class TwoTuple<A,B> {public final A first;public final B second;TwoTuple(A a,B b){first=a;second=b;}@Overridepublic String toString() {return "TwoTuple{" +"first=" + first +", second=" + second +", str='" + str + '\'' +'}';}public static void main(String[] args) throws Exception{TwoTuple<String,String> object = new TwoTuple<>("aaaa","aaa");System.out.println(object);}}
通过泛型和元组可以领其返回一个任意类型的对象
package com.package15;class Amphibian{}class Vehicle{}public class TupleTest {static TwoTuple<String,Integer> f(){return new TwoTuple<String,Integer>("hi",47);}static TwoTuple<Amphibian,Vehicle> info(){return new TwoTuple<>(new Amphibian(),new Vehicle());}public static void main(String[] args) {TwoTuple<String, Integer> f = f();System.out.println(f);TwoTuple<Amphibian, Vehicle> info = info();System.out.println(info);}}
结合泛型实现栈式存储机制
package com.package15;public class LinkedStatck<T> {private class Node<U> {U itme;//值域Node<U> netx;//指针Node() {itme = null;netx = null;}Node(U item, Node next) {this.itme = item;this.netx = next;}boolean end(){//判断是否结束return itme==null&&netx==null;}}private Node<T> top =new Node<T>();//哨兵机制,初始化一个空结点public void push(T item){top=new Node<>(item,top);/** 每次调用top方法的时候都回去新new 一个top对象。* */}public T pop(){T itme = top.itme;/** 此时的top刚好是最后一次添加的top对象,* 取一次并把指针指向前一个对象。指导遇到哨兵(空的top)这个时候栈已经为空了* */if (!top.end())//没有结尾的话top=top.netx;return itme;}public static void main(String[] args) {LinkedStatck<String> lk = new LinkedStatck<>();String str="Phasers on stun!";for (String s:str.split(" ")) {lk.push(s);}String srg;while ((srg=lk.pop())!=null)System.out.println(srg);}}
