转自:http://weblogs.java.net/blog/alexfromsun/archive/2011/05/05/swing-better-world-generics-and-arrays
Generics doesn't work well with arrays. Everybody knows that you can't create a generified array, but not many people really know what it was done this way. A nice article fromBrian Goetz
helped me to understand the problem when I studied the new features of JDK 5.
The arrays in java are covariant when generics are not. The following code clearly shows it:
String stringArray[] =
new
String[
1
];
// compiles ok
Object objectArray[] = stringArray;
// throws ArrayStoreException
objectArray[
0
] =
new
Object();
ArrayList<String> stringList =
new
ArrayList<String>();
// doesn't compile - incompatible types
ArrayList<Object> objectList = stringList;
If a generfied program is compiled without a warning you can safely add an Object to your ArrayList of Objects. However when there is an array of Objects passed to your method as a parameter, there is no way to understand an object of what type you can put there (I am not sure if you can find it out via reflection).
So it is known that arrays and generics don't do well together. It means that it is not recommended to use two features of JDK 5 together, I am talking about generics and
varargs
.
This reminds me one old bug found by
Rémi Forax
, which was fixed by changing
protected
void
process(V... chunks) {
}
to
protected
void
process(List<V> chunks) {
}
in the
SwingWorker
class, which did look awkward at the first glance.
An alternative implementation
I would be happy if I could create and safely use generified arrays in java, at the same time I can hardly remember if I ever saw a snippet of code that really benefited from the fact that arrays are covariant. This feature of java arrays doesn't look attractive to me and I don't mind "deprecating" it, I don't feel it is correct that I can't create a generifed array when I never cast an array of one particular type to an array of its supertype.
Certainly all java code must be backward compatible with any new version of JDK, I am thinking about a new warning produced by the compiler when covariant arrays are in use. If there is no such a warning in your code it should be pretty acceptable to create a generified array, otherwise you are warned just like when you use a raw type of a generifed class. Something to discuss for the next JDKs?
读后注:为什么要这样改参数呢?因为你已知数组与泛型支持不足,如果前者V是OBJECT,你如个STRING数组过去,这是编译不报错,但有隐含BUG,在方法内,你再以OBJECT对象去操作数组,这时就出错!而用后者LIST作参数,若V是OBJECT,然后你传个STRING的LIST,编译时就出错,很好地抵制隐含的BUG。这些论断已用程序验证过。
分享到:
相关推荐
本书"Java Generics and Collections"深入探讨了这两个主题,帮助开发者编写更安全、更高效且可维护的代码。 首先,让我们来理解Java泛型。泛型是Java 5引入的一项特性,它允许在类、接口和方法中使用类型参数。这...
- **集合间的转换**:通过`Arrays.asList()`等方法将数组转换为集合,或将集合转换为数组。 ### 结论 《Java泛型与集合》这本书不仅涵盖了Java泛型的基本概念和用法,还深入探讨了泛型的高级特性和集合框架的相关...
Updates to Java 5.0 include new sections on generics and other Java 5.0 features, and revised code fragments, examples, and case studies to conform to Java 5.0. Hundreds of exercises, including many...
* Strings and arrays * Flow control and exceptions * Assertions and Java 7 exceptions * String processing, data formatting, and resource bundles * I/O and NIO * Advanced OO and design patterns * ...
Updates to Java 5.0 include new sections on generics and other Java 5.0 features, and revised code fragments, examples, and case studies to conform to Java 5.0. Hundreds of exercises, including many...
Updates to Java 5.0 include new sections on generics and other Java 5.0 features, and revised code fragments, examples, and case studies to conform to Java 5.0. Hundreds of exercises, including many...
Covers challenging .NET features including Language Integrated Query (LINQ), LINQ to SQL, LINQ to XML, WCF, WPF, Workflow, and Generics Puts the new Async keyword to work and features refreshers on ...
Arrays Operators Control Flow Statements Error/Exception Handling Complex Example Interfaces and Inheritance Collections Generics Threads Summary Chapter 3 The Stack Stack Overview Linux Native Layer ...
• Discover powerful Swift features such as protocols and generics • Catch up on Swift 3 innovations: revised APIs, new Foundation bridged types, and more • Tour the lifecycle of an Xcode project ...
Chapter 5 Generics Chapter 6 Operators And Casts Chapter 7 Arrays Chapter 8 Delegates, Lambdas, And Events Chapter 9 Strings And Regular Expressions Chapter 10 Collections Chapter 11 Special ...
strings and characters, operators and functions, arrays and dictionaries, control flow, and looping, with expert guidance on classes, objects, class inheritance, closures, protocols, and generics....
Chapter 5: Arrays and Records Chapter 6: All About Strings Part II Chapter 7: Objects Chapter 8: Inheritance Chapter 9: Handling Exceptions Chapter 10: Properties and Events Chapter 11: Interfaces ...
includes advanced topics such as interfaces and lambda expressions, generics, collection classes and exceptions; explains file-handling techniques, packages, multi-threaded programs, socket ...
Then we explore more structured data such as strings, arrays, and enums, and you'll see how pattern matching works. Throughout all this, we stress the unique ways of reasoning that the Rust compiler...
- **Array Assignments**: Creating and initializing arrays, including multi-dimensional arrays. #### 4. Operators Operators are essential for performing operations on operands. This chapter explores:...
10 Using Arrays and Collections 191 11 Understanding Parameter Arrays 219 12 Working with Inheritance 231 13 Creating Interfaces and Defning Abstract Classes 253 14 Using Garbage Collection and ...