genericity(泛型)
来源:互联网 发布:人工智能 华伍 编辑:程序博客网 时间:2024/05/29 16:23
泛型的小结:
1.泛型的原型是Object,定义了泛型只是编译器在做一些验证工作,设置会检查,获取会自动转换,集合支持泛型,泛型约束集合元素。
2.内部原理2个(获取设置)和错误1个(类造型异常)和方便遍历(2个)
******************************************************************************************************
知识点1.(Point用于Test,加粗案例是易错点)
public class Point<T> {
private T x;
private T y;
public T getX() {
return x;
}
public void setX(T x) {
this.x = x;
}
public T getY() {
return y;
}
public void setY(T y) {
this.y = y;
}
public Point(T x, T y) {
super();
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
public class demo1 {
public static void main(String[] args) {
// 指定是Integer,创建时是Object类型。只是当成Integer看待
Point<Integer> p1=new Point<Integer>(1,2);
p1.setX(1);//编译器验证
int x1=p1.getX();//自动转换加拆箱
Point p2=p1;//没加泛型
p2.setX("一");
String x2=(String)p2.getX();
System.out.println("x2:"+x2);
x1=p1.getX();
System.out.println("x1:"+x1);//p2改了x,p1获取x又自动转换,发现类造型异常
}
}
public class demo2 {
public static void main(String[] args) {
Collection<String> c=new ArrayList<String>();
c.add("一");//约束了添加元素
//遍历集合元素
for(String str: c){
System.out.println(str);
}
// 迭代器也指定泛型,泛型的实际类型,应当与它遍历的集合的泛型类型一致
Iterator<String> it=c.iterator();
while(it.hasNext()){
String str=it.next();//获取元素时不需要再造型了
System.out.println(str);
}
}
}
- genericity(泛型)
- 泛型(genericity)
- Genericity/STL 大系
- 学习笔记之genericity
- 侯捷书评【Genericity/STL 大系】
- The advance of Java -- Genericity, Exception, IO(Day04)
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- Nginx入门案例(Mac版)
- 第11章 晚期(运行期)优化
- 常用端口及其所代表的协议
- BZOJ2034最大收益 [贪心优化特殊图最优匹配]
- ApplicationContext AlertDialog IllegalStateException: You need to use a Theme.AppCompat theme
- genericity(泛型)
- ios多线程浅谈和使用
- AutoCAD 记录
- 程序员不能错过的技术知识图谱,进阶路上必备神器。
- 博洁在线盈利平台系统开发定制
- JavaScript实现H5游戏断线自动重连的技术
- 深入理解分布式事务,高并发下分布式事务的解决方案
- Gym
- APUE读书笔记-第十一章-线程