您的位置:首页 > 编程语言 > Java开发

JAVA——泛型

2016-05-09 00:30 537 查看
泛型:JDK1.5以后出现的新特性。用于解决安全问题,是一个安全机制;

好处:

1、将运行时期出现问题classCastException,转移到了编译期间,方便于程序员解决问题,让运行时问题减少,安全

2、避免了强制转换麻烦

泛型格式:通过<>来定义要操作的引用数据类型。

在使用java提供的对象时,什么时候写泛型呢?

通常在集合框架中很常见;

其实<>就是用来接收类型的。

当使用集合时,将集合中要存储的数据类型作为参数传递到<>中即可。

import java.util.*;
class GenericDemo
{
public static void main(String[] args)
{
ArrayList al = new ArrayList();
al.add("hello");
al.add("pp");
al.add("I love you !");
al.add(3);

Iterator it = al.iterator();
while(it.hasNext())
{
String s = (String)it.next();
System.out.println(s+"..."+s.length());
}
}
}


出现了这个情况,为什么呢?

注: /Users/wangliqiang/Desktop/JAVA/BXD/GenericDemo.java使用了未经检查或不安全的操作。
注: 有关详细信息, 请使用 -Xlint:unchecked 重新编译。
hello...5
pp...2
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at GenericDemo.main(GenericDemo.java:22)
I love you !...12


因为 al.add(3);系统自动装箱会new Integer(3);变为Integer对象。但是,迭代器中存放了添加进去的元素。

Iterator it = al.iterator();

String s = (String)it.next();

这样会ClassCastException;

所以我们可以这么做:

class GenericDemo
{
public static void main(String[] args)
{
ArrayList <String>al = new ArrayList<String>();
al.add("hello");
al.add("bb");
al.add("I love you !");

Iterator <String>it = al.iterator();
while(it.hasNext())
{
String s = it.next();
System.out.println(s+"..."+s.length());
}
}
}


结果:

hello…5

bb…2

I love you !…12
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: