Java泛型总结(七)

2014-11-24 03:08:01 · 作者: · 浏览: 7
从Object转换为他们真是的类型。考察下边的java1.4的代码。
public static void main(String[] args) {
// This list is intended to hold only strings.
// The compiler doesn't know that so we have to remember ourselves.
List wordlist = new ArrayList();
// Oops! We added a String[] instead of a String.
// The compiler doesn't know that this is an error.
wordlist.add(args);
// Since List can hold arbitrary objects, the get() method returns
// Object. Since the list is intended to hold strings, we cast the
// return value to String but get a ClassCastException because of
// the error above.
String word = (String)wordlist.get(0);
}
泛型类型解决了这段代码中的显示的类型安全问题。Java.util中的List或是其他集合类已经使用泛型重写过了。就像前面提到的, List被重新定义为一个list,它中间的元素类型被一个类型可变的名称为E的占位符描述。Add()方法被重新定义为期望一个类型为E的参数,用于替换以前的Object,get()方法被重新定义为返回一个E,替换了以前的Object。
在java5.0中,当我们申明一个List或者创建一个ArrayList的实例的时候,我们需要在泛型类型的名字后面紧跟一对“<>”,尖括号中写入我们需要的实际的类型。比如,一个保持String的List应该写成“List”。需要注意的是,这非常象给一个方法传一个参数,区别是我们使用类型而不是值,同时使用尖括号而不是圆括号
Java.util的集合类中的元素必须是对象化的,他们不能是基本类型。泛型的引入并没有改变这点。泛型不能使用基本类型:我们不能这样来申明——Set或者List。记住,无论如何,java5.0中的自动打包和自动解包特性使得使用Set或者List和直接使用char和int值一样方便。
在Java5.0中,上面的例子将被重写为如下方式:
public static void main(String[] args) {
// This list can only hold String objects
List wordlist = new ArrayList();
// args is a String[], not String, so the compiler won't let us do this
wordlist.add(args); // Compilation error!
// We can do this, though.
// Notice the use of the new for/in looping statement
for(String arg : args) wordlist.add(arg);
// No cast is required. List.get() returns a String.
String word = wordlist.get(0);
}
值得注意的是代码量其实并没有比原来那个没有泛型的例子少多少。使用“(String)”这样的类型转换被替换成了类型参数“”。不同的是类型参数需要且仅需要声明一次,而list能够被使用任何多次,不需要类型转换。在更长点的例子代码中,这一点将更加明显。即使在那些看上去泛型语法比非泛型语法要冗长的例子里,使用泛型依然是非常有价值的——额外的类型信息允许编译器在您的代码里执行更强的错误检查。以前只能在运行起才能发现的错误现在能够在编译时就被发现。此外,以前为了处理类型转换的异常,我们需要添加额外的代码行。如果没有泛型,那么当发生类型转换异常的时候,一个ClassCastException异常就会被从实际代码中抛出。
就像一个方法可以使用任意数量的参数一样,类允许使用多个类型变量。接口Java.util.Map就是一个例子。一个Map体现了从一个key的对象到一个value的对象的映射关系。接口Map申明了一个类型变量来描述key的类型而另一个类型变量来描述value的类型。举个例子来说,假设您希望做一个String对象到Integer对象的映射关系:
public static void main(String[] args) {
// A map from strings to their position in the args[] array
Map map = new HashMap();
// Note that we use autoboxing to wrap i in an Integer object.
for(int i=0; i < args.length; i++)
map.put(args[i], i);
// Find the array index of a word. Note no cast is required!
Integer position = map.get("hello");
// We can also rely on autounboxing to convert directly to an int,
// but this throws a NullPointerException if the key does not exist in the map
int pos = map.get("world");
}
象List这个一个参数类型其本身也是也一个类型,也能够被用于当作其他类型的一个类型变量值。您可能会看到这样的代码:
// Look at all those nested angle brackets!
Map>> map = getWeirdMap();
// The compiler knows all the types and we can write expressions
// like this without casting. We might still get NullPointerException
// or ArrayIndexOutOfBounds at runtime, of course.
int value = map.get(key).get(0).get(0)[0];

// Here's how we break that expression down step by step.
List> listOfLists = map.get(key);
List listOfIntArrays = listOfLists.get(0);
int[] array = listOfIntArrays.get(0);
int element = array[0];
在上面的代码里,java.util.List和java.util.Map的get()方法返回一个类型为E的list元素或者一个类型为V的map元素。注意,无论如何,泛型类型能够更精密的使用他们的变量。在本书中的参考章节查看List,您将会看到它的iterator( )方法被声明为返回一个Iterator。这意味着,这个方法返回一个跟list的实际的参数类型一样的一个参数类型的实