Generics的用法

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package andy.chen.chart;


import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
* @date 2009-5-27
* @author andychen
*/
public class Example {
//建立一个集合类

protected void collectionExample() {
ArrayList<String> al = new ArrayList();//该实例实现了Generics
// HashMap<Integer,String> map = new HashMap<Integer,String>();
// map.put(1,"sdf");
// String name = map.get(1);

// ArrayList al = new ArrayList();
al.add(new String("df"));
// al.add(new Integer(2));
inpectCollection(al);

}
/*collection 是object类型,需要类型转换,运行会出现ClassCastException异常
* 这个时候就需要用到Generics(范型):由编译器来验证从客户端将一种类型传送给某一对象的机制
* 目的是为了增加类型安全
* 1.在类型没有变化时,Collection是类型安全的。
* 2.内在的类型转换优于在外部的人工造型。
* 3.使Java 接口更加强壮,因为它增加了类型。
* 4.类型的匹配错误在编译阶段就可以捕捉到,而不是在代码运行时。
*将具体的类型转化为object类型是,不能编译,会报错,此时可用通配符?
* void printCollection(Collection<?> c)
*{ for (Object e : c) {
*System.out.println(e);
*}}

* object ob ob.getClass().getName()
*/

protected void inpectCollection(Collection<String> acollection) {
Iterator<String> i = acollection.iterator();
// Iterator i = acollection.iterator();
while (i.hasNext()) {
String str = i.next();
// String str = (String)i.next();
}

}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值