<T> List<T>前面<T>的意思
先看例子:
import java.util.*;
class Fruit { public String toString() { return "Fruit"; } }
class Apple extends Fruit { public String toString(){ return "Apple"; } }
class Person { public String toString(){ return "Person"; } }
class ClassName<T> {//主类,文件名ClassName.java
void show_1(T t){
System.out.println("show_1 "+ t.toString());
}
<E> void show_2(E e){
System.out.println("show_2 "+e.toString());
}
<T> void show_3(T t){
System.out.println("show_3 "+t.toString());
}
public static void main(String[] args) {
ClassName<Fruit> o = new ClassName<Fruit>();
Fruit f = new Fruit();
Apple a = new Apple();
Person p = new Person();
System.out.println("show_1 演示________________________");
o.show_1( f );
o.show_1( a );
// o.show_1( p ); 这行代码是不能编译通过的。因为在
// ClassName<Fruit>中已经限定了全局的T为Fruit,所以不能再加入Person;
System.out.println("show_2 演示________________________");
o.show_2( f );
o.show_2( a );
o.show_2( p );
System.out.println("show_3 演示________________________");
o.show_3( f );
o.show_3( a );
o.show_3( p );
}
}
程序输出:
show_1 演示________________________
show_1 Fruit
show_1 Apple
show_2 演示________________________
show_2 Fruit
show_2 Apple
show_2 Person
show_3 演示________________________
show_3 Fruit
show_3 Apple
show_3 Person
show_2 和show_3方法其实是完完全全等效的。意思就是说ClassName<T>中一旦T被指定为Fruit后那么show_1没有前缀<T> 的话,该方法中只能是show_1 (Fruit对象)
要是有前缀<T>或<E>的话,那么就是告诉编译器:这是新指定的一个类型,跟ClassName<T>类对象中的T没有半毛钱的关系。也就是说这个show_3中的T和show_2中的E是一个效果,也就是可以把show_3同等程度地理解为<E> void show_3(E e){~~~~~}
摘自:泛型里面的<T> List<T>前面的<T>代表是什么意思?为什么要加<T>?
随机推荐
- [整理]在命令行执行 UIAutomation
instruments -t /Developer/Platforms/iPhoneOS.platform/Developer/Library/Instruments/PlugIns/Automati ...
- 几行实现圆形头像,以及一些常见需求形状自定义ImageView组件
在实际开发中,我们经常会遇到这样的需求,就是无论图片长啥样,我们都要其显示成圆形.圆形加一个边框.矩形加边框,带圆角的矩形等等,我已把自己平常用的组件和demo上传到了github(https://g ...
- ios学习之路四(新建Sprite Kit 项目的时候出现apple LLVM 5.0 error)
在新建sprite kit 项目的时候出现"apple LLVM 5.0 error" 解决方法 在网上搜索,stackoverflow 上是这么说的点击打开链接.按照他的我也没解 ...
- 初探中间件(middleware)
初探中间件(middleware) 因为考虑到文章的长度, 所以 BaseHandler 的展开被推迟了. 在 BaseHandler 中隐藏着中间件的信息, 较常见的 SessionMiddlewa ...
- JavaEE:Tomcat服务器常用配置和HTTP简介
Web服务器常用配置1.Web系统采用B/S结构通信的:Browser --- Server1)浏览器向服务器发送访问目标资源请求(请求)2)服务器根据请求的目标资源路径,在服务器端进行查找(请求查找 ...
- QSQL导出mapfile和mapfile中PostGIS连接的一点心得
昨天弄QSQL导出mapfile,一直遇到下图的错误 原因是QGIS在渲染图层时候使用了新的符号,在图层上右键-属性,如下图将符号修改就OK了 然后我尝试使用QGIS连接本机PostGIS数据,结果老 ...
- spring添加通知配置
在项目里添加的spring配置文件 <bean id="beforeMethod" class="com.wxw.core.common.AdviceBefore& ...
- zookeeper使用跟原理
zookeeper使用和原理 zookeeper介绍zookeeper是一个为分布式应用提供一致性服务的软件,它是开源的Hadoop项目中的一个子项目,并且根据google发表的<The Chu ...
- 设计模式之 - 工厂方法模式 (Factory Method design pattern)
1. 模式意图: 定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法使一个类的实例化延迟到其子类. 2. 别名(Virtual Constructor) 3. 结构 4. 工厂方法模式C ...
- JVM方法调用栈
摘自深入分析java web技术内幕