Java泛型方法的使用

 

在方法上使用泛型,不要求所在的类使用泛型,更灵活;

package com.mldn;

 

class Demo

{

public T print(T param) // 泛型方法:所在的类非泛型操作类

{

return param; // 返回值也是泛型

}

}

 

public class GenDemo2

{

public static void main(String[] args)

{

String str = new Demo().print(“返回泛型!”); // T–>String

int i = new Demo().print(5); // T–>Integer

Demo demo = new Demo().print(new Demo()); // T–>Demo

Demo demo1 = new Demo();

 

System.out.println(str + “\n” + i + “\n” + demo + “\n” + demo1.print(demo1));

}

}

/*

administrator@xu-desktop:~$ javac -d . ./work/GenDemo2.

administrator@xu-desktop:~$ com.mldn.GenDemo2

返回泛型!

5

com.mldn.Demo@3e25a5

com.mldn.Demo@19821f

 

*/

 

声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 智乐兔
转载请注明:转自《Java泛型方法的使用
本文地址:https://www.zhiletu.com/archives-61.html
关注公众号:智乐兔

赞赏

wechat pay微信赞赏alipay pay支付宝赞赏

上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!

在线客服
在线客服 X

售前: 点击这里给我发消息
售后: 点击这里给我发消息

智乐兔官微