1.泛型方法的定义和语法
1.1 定义
泛型方法 是在 调用方法 的时候指明泛型的具体类型。
【泛型方法 能够使方法独立于类的处理指定的类型。】
1.2 语法
修饰符 <t,e,…> 返回值类型 方法名(形参列表){ 。。。。。。 }
修饰符与返回值类型中间的 泛型标识符 <t,e,…>,是 泛型方法的标志,只有这种格式声明的方法才是泛型方法。
泛型方法声明时的 泛型标识符 <t,e,…> 表示在方法可以使用声明的泛型类型。
与泛型类相同,泛型标识符可以是任意类型,常见的如t,e,k,v 等。
泛型方法可以声明为 static 的,并且与普通的静态方法是一样的。
2.泛型方法的使用
2.1 普通泛型方法
- 声明
/** * author : northcastle * createtime:2021/10/23 * 泛型方法的定义 */ public class genericmethod { //1.普通的泛型方法 public <t> string commonmethod(string name,t t){ string res = ""; res += name +"-"+ t; system.out.println("普通泛型方法 : "+res); return res; } }
- 调用
/** * author : northcastle * createtime:2021/10/23 */ public class genericmethodapplication { public static void main(string[] args) { //1.调用普通泛型方法 genericmethod genericmethod = new genericmethod(); string commonres01 = genericmethod.commonmethod("001", "bb"); system.out.println(commonres01); string commonres02 = genericmethod.commonmethod("002", 100); system.out.println(commonres02); string commonres03 = genericmethod.commonmethod("003", true); system.out.println(commonres03); system.out.println("=================="); } }
- 运行结果
普通泛型方法 : 001-bb
001-bb
普通泛型方法 : 002-100
002-100
普通泛型方法 : 003-true
003-true
==================
2.2 静态泛型方法
- 声明
/** * author : northcastle * createtime:2021/10/23 * 泛型方法的定义 */ public class genericmethod { //2.静态的泛型方法 public static <t,e> string staticmethod(string name,t t,e e){ string res = ""; res += name +"-"+ t +"-"+ e; system.out.println("静态泛型方法 : "+res); return res; } }
- 调用
package com.northcastle.genericmethod; /** * author : northcastle * createtime:2021/10/23 */ public class genericmethodapplication { public static void main(string[] args) { //2.调用静态泛型方法 string staticres01 = genericmethod.staticmethod("001", "aa", "bb"); system.out.println(staticres01); string staticres02 = genericmethod.staticmethod("002", 100, 'c'); system.out.println(staticres02); string staticres03 = genericmethod.staticmethod("003", 12.05d, false); system.out.println(staticres03); system.out.println("=================="); } }
- 运行结果
静态泛型方法 : 001-aa-bb
001-aa-bb
静态泛型方法 : 002-100-c
002-100-c
静态泛型方法 : 003-12.05-false
003-12.05-false
==================
2.3 泛型方法中的可变参数
- 声明
/** * author : northcastle * createtime:2021/10/23 * 泛型方法的定义 */ public class genericmethod { //3.带可变参数的泛型方法 public <a> void argsmethod(a ... args){ for (a arg : args) { system.out.println(arg); } } }
- 调用
package com.northcastle.genericmethod; /** * author : northcastle * createtime:2021/10/23 */ public class genericmethodapplication { public static void main(string[] args) { //3.调用可变参数的方法 genericmethod.argsmethod(1,2,300,400,500,600); system.out.println("=================="); } }
- 运行结果
1
2
300
400
500
600
==================
完成~
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论