Java重要技术(19)泛型之泛型的使用方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java重要技术(19)泛型之泛型的使用方法相关的知识,希望对你有一定的参考价值。

1.1. 泛型的用法

参数化类型比如Sample<T>中的类型参数T可以用于构造函数的参数的类型,方法的返回值的类型,画着方法的参数的类型,属性字段的类型等。

public class GenericParameterTest {

 

//参数化类型T,可以为String,Integer等引用类型。

static class  Sample<T> {

public Sample(T obj){

this.obj = obj;

}

 

//参数化类型作为返回值的类型。

public T work(){

System.out.println("work:"+this.obj);

return this.obj;

}

 

//参数化类型作为参数的类型。

public void update(T obj){

this.obj = obj;

}

 

 

//参数化类型作为属性的类型。

private T  obj;

 

}

 

public static void main(String[] args) {

 

//正确用法。T是String。

Sample<String>  sample = new Sample<String>("Hello");

String obj = sample.work();

sample.update("world");

obj = sample.work();

System.out.println(obj);

 

//语法错误。错误用法。

//Sample<int>  anotherSample = new Sample<int>(1);

 

//正确用法。T是Integer.

Sample<Integer> anotherSample = new Sample<Integer>(1);

 

 

}

 

 

 

 

运行结果如下:

work:Hello

work:world

world

 

以上是关于Java重要技术(19)泛型之泛型的使用方法的主要内容,如果未能解决你的问题,请参考以下文章

Java基础 -- 泛型之泛型参数

泛型之泛型方法

javaSE之泛型(Generics)

Java基础之泛型的使用

java之泛型的使用

Java基础之泛型