Java泛型类与泛型函数

泛型:所操作的数据类型被指定为一个参数,即数据类型参数化。避免重复写类似的功能代码。

package com.example.javatest;//包名定义

/**
 * Author:W
 * 泛型:所操作的数据类型被指定为一个参数,数据类型参数化。
 * 1)泛型类:在类名后面添加了类型参数声明部分。
 * 2)泛型方法:该方法在调用时可以接收不同类型的参数。根据传递给泛型方法的参数类型,编译器适当地处理每一个方法调用。
 */

public class MainTest{

    public static void main(String[] args)
    {
          System.out.println("===泛型类===");
          Ttest<Integer>  test1 = new Ttest<Integer>();
          test1.setT(4);
          System.out.println("泛型类 Integer时,t值为"+test1.getT());
          Ttest<String>  test2 = new Ttest<String>();
          test2.setT("Hello");
          System.out.println("泛型类 String 时,t值为"+test2.getT());

          System.out.println("===泛型方法===");
          System.out.println("2和3的最大值:"+max(2,3));
          System.out.println("H和A的最大值:"+max("H","A"));
    }

    //泛型方法
    private static <T extends Comparable<T> > T max(T a,T b)
    {
        T  max = null;
        max = (a.compareTo(b) > 0) ? a:b;
        return max;
    }
}
package com.example.javatest;

/**
 * Author:W
 * 泛型类
 * T extends Comparable<T>
 * T是指类型参数
 * extends Comparable<T>:是对类型参数的类型种类范围的限制
 */
public class Ttest<T extends Comparable<T>> {

    public T   t;

    public  void  setT(T t)
    {
        this.t = t;
    }

    public  T getT()
    {
        return this.t;
    }
}

运行结果如下:

猜你喜欢

转载自blog.csdn.net/hppyw/article/details/119653512