欢迎来到山村网

Java中泛型使用

2019-03-02 11:35:08浏览:885 来源:山村网   
核心摘要:  泛型: 1.5 之后出现 提高安全 1 泛型 确定 集合容器的类型。 2接收一种数据类型,(引用数据类型) ArrayListlis = new Array

  泛型: 1.5 之后出现 提高安全 1 泛型 确定 集合容器的类型。 2 <> 接收一种数据类型,(引用数据类型) ArrayList lis = new ArrayList() 目的: 将运行时期的 错误 转化到 编译时期,提高了安全性! 3 不需要 强制类型转换. 更加安全!

  泛型的 擦除: 泛型在编译时期使用!使用完毕直接擦除。 编译完的时候 不存在 泛型。

  好处: 使用了 泛型,不自需要强制类型转换?(多种数据类型) 为什么? 因为容器中只有一种数据类型。 取出数据之后,在处理数据细节!String 就是 很重要的。在现实的开发中。

  泛型自定义的类:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 //使用泛型 class Tools<t> { private T obj; public void setObject(T obj) { this.obj = obj; } public T getObject() { return this.obj; } }</t>

  泛型应用在方法上:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class Test<e> { //泛型用在方法上 //当类中的某个方法所使用的类型只有在类上的类型确定了才能确定时,就在方法上使用 //泛型 //否则不用泛型 public void func(E e) { System.out.println(e); } //该方法单独使用泛型: 方法使用的类型不确定,而且什么类型都行 //这个 方法被调用时,类型才确定 public <t> void show(T e) { System.out.println(e); } //静态是随着类的加载而加载,这是不存在类型,所以静态方法只能自己定义泛型 public static <w> void function(W e)//Test.function() { System.out.println(e); } public void ff(int a,int b) { System.out.println(a+b); } }</w></t></e>

  泛型 定义在接口上:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 //泛型用在接口上 interface inter<t> { public void show(T t); } class Test implements inter<string> { public void show(String t) { } } class Demo<e> implements inter<e> { public void show(E t) { System.out.println(t); } } class Demo9 { public static void main(String[] args) { Demo<string> d = new Demo<string>(); d.show(99);// error } } </string></string></e></e></string></t>
(责任编辑:豆豆)
下一篇:

微信小店分类ID列表

上一篇:

java实现屏幕取色

  • 信息二维码

    手机看新闻

  • 分享到
打赏
免责声明
• 
本文仅代表作者个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,作者需自行承担相应责任。涉及到版权或其他问题,请及时联系我们 xfptx@outlook.com