示例代码:
- class Gen<T extends Number>{ //泛型类T是泛型类型形参 extends Number约束类型
- T ob; //声明对象ob
- Gen(T o){ //构造方法
- ob=o;
- }
- <T extends Number>Gen(T o){ //泛型构造
- }
- T getob() { //返回T类型
- return ob;
- }
- void showType() {
- System.out.println("Type of T is: "+ob.getClass().getName());
- }
- }
- public class GenDemo {
- public static void main(String[] args) {
- Gen<Integer> iOb=new Gen<Integer>(88); //Integer类型的引用
- iOb.showType();
- int v=iOb.getob();
- System.out.println("value: "+v);
- Gen<String> strOb=new Gen<String>("Generics Test.");//String类型的引用
- strOb.showType();
- String str=strOb.getob();
- System.out.println("value: "+str);
- }
- }
- ----------------------------------------------------------------------------------------------
- 带有两个类型形参的泛型类
- class TwoGen<T,V>{
- T ob1;
- V ob2;
- TwoGen(T o1,V o2){
- ob1=o1;
- ob2=o2;
- }
- void showTypes() {
- System.out.println("Type of T is "+ob1.getClass().getName());
- System.out.println("Type of V is "+ob2.getClass().getName());
- }
- T getob1() {
- return ob1;
- }
- V getob2() {
- return ob2;
- }
- boolean isSame(TwoGen<T,V> o) {
- if(ob1==o.ob1&&ob2==o.ob2) {
- return true;
- }else {
- return false;
- }
- }
- }
- public class SimpGen {
- public static void main(String[] args) {
- TwoGen<Integer,String> tgObj=new TwoGen<Integer,String>(88,"Generics");
- tgObj.showTypes();
- int v=tgObj.getob1();
- System.out.println("Value: "+v);
- String str=tgObj.getob2();
- System.out.println("Value: "+str);
- TwoGen<Integer,String> tt=new TwoGen<>(77,"hello world");//<>泛型类型推断
- System.out.println(tt.getob1()+" "+tt.getob2());
- System.out.println(tt.isSame(new TwoGen<>(67,"hello world")));
- }
- }
- ---------------------------------------------------------------------------
- 通配符实参?
- boolean absEqual(Numeric<?> ob) {
- if(Math.abs(num.doubleValue())==Math.abs(ob.num.doubleValue())) {
- return true;
- }else {
- return false;
- }
- }
- --------------------------------------------------------------------------
- 泛型接口
- public interface IGenQ<T> {
- void put(T ch) throws QueueFullException;
- T get() throws QueueEmptyException;
- }
- ---------------------------------------------------------------------------
- 愿类型和遗留代码:非泛型代码能够处理泛型代码,泛型代码能够处理非泛型代码
- public class RawDemo {
- public static void main(String[] args) {
- Gen<Integer> iOb=new Gen<Integer>(88);
- System.out.println(iOb.getob());
- Gen<String> strOb=new Gen<String>("Generics Test");
- System.out.println(strOb.getob());
- Gen raw=new Gen(new Double(98.6));//不提供类型实参时,创建原类型
- double d=(Double)raw.getob();
- System.out.println("value: "+d);
- Gen rbw=new Gen(new Integer(77));
- int i=(Integer)rbw.getob();
- System.out.println(i);
- }
- }