实例解析-范型程序开发

来源:互联网 发布:恒大足校 知乎 编辑:程序博客网 时间:2024/05/21 01:56
实例说话:
范型类:
package belief.teach1.generic;

class Generic<T, U> {
    
/*
     * T,U,S表示任意类型 K,V表示键类型和值类型
     
*/

    
private T temp1;

    
private U temp2;

    
public void setValue(T temp1, U temp2) {
        
this.temp1 = temp1;
        
this.temp2 = temp2;
    }


    
public T getTemp1() {
        
return this.temp1;
    }


    
public U getTemp2() {
        
return this.temp2;
    }


}


public class GenericClass {

    
public static void main(String args[]) {
        Generic
<String, Integer> g1 = new Generic<String, Integer>();
        g1.setValue(
"字符串"new Integer(10));
        String str1 
= g1.getTemp1();
        Integer num 
= g1.getTemp2();
        System.out.println(
" " +str1+";"+num);
    }

}
范型类可以有多个变量,这些变量在调用时可以动态指定.范型接口原理也和范型类相同。


范型方法:
package belief.teach1.generic;

public class GenerticFunction {
    
    
public static <U> U getFirst(U[] a){
        
return a[0];
    }


    
public static void main(String[] args){
        
        String[] a
={"first","second","third"};
        String strFirst
=GenerticFunction.getFirst(a);
        System.out.println(
"strFirst="+strFirst);
        
    }

}

 

调用范型方法是可以明确给出参数,也可以不给出,系统会自动分析确定。