小白教程

 找回密码
 立即注册
小白教程 首页 系列教程 Java系列教程 查看内容

Java 泛型

发布者: 小白教程



实例

下面的例子演示了 "extends" 如何使用在一般意义上的意思 "extends"(类)或者"implements"(接口)。该例子中的泛型方法返回三个可比较对象的最大值。

  1. public class MaximumTest
  2. {
  3. // 比较三个值并返回最大值
  4. public static <T extends Comparable<T>> T maximum(T x, T y, T z)
  5. {
  6. T max = x; // 假设x是初始最大值
  7. if ( y.compareTo( max ) > 0 ){
  8. max = y; //y 更大
  9. }
  10. if ( z.compareTo( max ) > 0 ){
  11. max = z; // 现在 z 更大
  12. }
  13. return max; // 返回最大对象
  14. }
  15. public static void main( String args[] )
  16. {
  17. System.out.printf( "Max of %d, %d and %d is %d\n\n",
  18. 3, 4, 5, maximum( 3, 4, 5 ) );
  19. System.out.printf( "Maxm of %.1f,%.1f and %.1f is %.1f\n\n",
  20. 6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ) );
  21. System.out.printf( "Max of %s, %s and %s is %s\n","pear",
  22. "apple", "orange", maximum( "pear", "apple", "orange" ) );
  23. }
  24. }

编译以上代码,运行结果如下所示:

  1. Maximum of 3, 4 and 5 is 5
  2. Maximum of 6.6, 8.8 and 7.7 is 8.8
  3. Maximum of pear, apple and orange is pear

泛型类

泛型类的声明和非泛型类的声明类似,除了在类名后面添加了类型参数声明部分。

和泛型方法一样,泛型类的类型参数声明部分也包含一个或多个类型参数,参数间用逗号隔开。一个泛型参数,也被称为一个类型变量,是用于指定一个泛型类型名称的标识符。因为他们接受一个或多个参数,这些类被称为参数化的类或参数化的类型。

实例

如下实例演示了我们如何定义一个泛型类:

  1. public class Box<T> {
  2. private T t;
  3. public void add(T t) {
  4. this.t = t;
  5. }
  6. public T get() {
  7. return t;
  8. }
  9. public static void main(String[] args) {
  10. Box<Integer> integerBox = new Box<Integer>();
  11. Box<String> stringBox = new Box<String>();
  12. integerBox.add(new Integer(10));
  13. stringBox.add(new String("Hello World"));
  14. System.out.printf("Integer Value :%d\n\n", integerBox.get());
  15. System.out.printf("String Value :%s\n", stringBox.get());
  16. }
  17. }

编译以上代码,运行结果如下所示:

  1. Integer Value :10
  2. String Value :Hello World
12
上一篇:Java 集合框架下一篇:Java 序列化

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-9-20 06:26 , Processed in 0.021983 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部