JavaSE5.0中增加了一组“被检验”的视图,用来对泛型类型发生问题时提供调试支持。在实际的编程实践中,将错误类型的元素私自带到泛型集合中的问题极有可能发生。例如:
ArrayList<String> strs = new ArrayList<String>();
ArrayList date = strs;
date.add(new Date());
String s = (String) date.get(0);
程序在运行的过程中将在第四行报错:
Exception in thread "main" java.lang.ClassCastException: java.util.Date cannot be cast to java.lang.String
所以在实际的项目开发中我们可以采用下面这种方式来杜绝此类事件的发生:
ArrayList<String> strs = new ArrayList<String>();
List<String> safeStrings = Collections.checkedList(strs, String.class);
List<String> rawType = safeStrings;
rawType.add(new Date());
这样,编译器在第四行将对程序提示错误:The method add(String) in the type List<String> is not applicable for the arguments (Date)。
这样我们就能轻而易举地发现错误所在了。
其中Collections的checkedList()方法就是把一个List视图声明为被检验视图,编译器就能在程序视图对其进行add操作时检查参数的类型。
当然,归根结底,我们写程序时最好还是要使用安全的方式,在声明集合的视图时指明集合的类型,如下:
ArrayList<String> strs = new ArrayList<String>();
ArrayList<String> date = strs;
date.add(new Date());
String s = (String) date.get(0);
这样的话编译器在第三行会提示错误,bug也就不会留到程序运行到get时才出现了。