泛型
2015-06-26 17:48
190 查看
泛型 构造方法中使用
class Gener<T>{ private T value; public T getValue() { return value; } public void setValue(T value) { this.value = value; } public String toString(){ return this.getValue().toString(); } } public class Demo01 { public static void main(String[] args) { // TODO Auto-generated method stub Gener<String> g = new Gener<String>(); g.setValue("Hello World"); say(g); } public static void say(Gener<?> g){ System.out.println(g.toString()); } }
泛型 通配符的使用:
使用泛型时,如果事先不知道是什么类型,可以使用?通配符
class Gener<T>{ private T value; public T getValue() { return value; } public void setValue(T value) { this.value = value; } public String toString(){ return this.getValue().toString(); } } public class Demo01 { public static void main(String[] args) { Gener<String> g = new Gener<String>(); g.setValue("Hello World"); say(g); } public static void say(Gener<?> g){ System.out.println(g.toString()); } }
泛型接口:
interface Gener1<T> { public void say(); } class Gar<T> implements Gener1<T> { private String value; public Gar(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public void say() { } } public class Demo02 { public static void main(String[] args) { // TODO Auto-generated method stub Gar<String> g = new Gar<String>("Hello World"); System.out.println(g.getValue()); } }
泛型方法:
泛型方法中可以定义泛型参数,此时,参数的类型就是传入数据类型
class Genera { public <T> T say(T t) { return t; } } public class Demo03 { public static void main(String[] args) { Genera g = new Genera(); String result = g.say("Hello World"); int result1 = g.say(10); System.out.println(result); System.out.println(result1); } }
泛型数组:
public class Demo04 { public static void main(String[] args) { Integer arr[] = { 1, 2, 3, 4 }; d(arr); String a[] = { "Hello", "World", "Gracy" }; d(a); } public static <T> void d(T arr[]) { for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
相关文章推荐
- Restore IP Addresses——边界条件判定
- ubuntu学习教程
- 文章收集
- 网络营销:产品卖点是核心营销方式
- Unity3d好文汇总
- Linux 上网络监控工具 ntopng 的安装
- Apache下PHP Loaded Configuration File None 解决方法
- TCP/IP协议三次握手与四次握手流程解析
- Hibernate的检索方式详解(二)
- QQ客服代码(支持临时会话设置)
- Lucene.Net 2.3.1开发介绍 —— 四、搜索(三)
- mac 上快速安装 MongoDB
- Skype for Business Server 2015标准版部署
- Web前端开发与iOS终端开发的异同
- 关于UNITY5.0和高通AR4.2.3在手机上白屏的问题
- WPF将数据库和GridView绑定并更改GridView模板
- 简明 Git 命令速查表
- HTTP协议的结构
- Hibernate的检索方式详解(一)
- 抽象与接口的综合练习