Generics的用法

xiaoxiao2026-05-28  5

/* * 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(); } } }
转载请注明原文地址: https://www.6miu.com/read-5049534.html

最新回复(0)