转自: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。这些论断已用程序验证过。
分享到:
相关推荐
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...
Protocols, extensions, and generics Memory management Closures: similar to blocks in Objective-C and lambdas in C# Optionals: values that can explicitly have no value Operators, operator overloading, ...
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 ...
Chapter 14 GENERICS AND THE ArrayList CLASS 759 Chapter 15 LINKED DATA STRUCTURES 801 Chapter 16 COLLECTIONS, MAPS AND ITERATORS 897 Chapter 17 SWING I 941 Chapter 18 SWING II 1017 Chapter 19 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...
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 ...
Chapter 7: Arrays and Tuples Chapter 8: Operators and Casts Chapter 9: Delegates, Lambdas, and Events Chapter 10: Strings and Regular Expressions Chapter 11: Collections Chapter 12: Special ...
Step-by-step, you’ll move from basic syntax through advanced features such as closures and generics–discovering helpful tips and tricks along the way. After you’ve mastered Swift’s building blocks...
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 ...
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....
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...
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 ...
Become familiar with built-in Swift types such as numbers, strings, ranges, tuples, Optionals, arrays, dictionaries, and sets Learn how to declare, instantiate, and customize Swift object types—enums...
Become familiar with built-in Swift types such as numbers, strings, ranges, tuples, Optionals, arrays, dictionaries, and sets Learn how to declare, instantiate, and customize Swift object types: enums...
Discover powerful Swift features such as protocols and generics Catch up on Swift 2.0 innovations: option sets, protocol extensions, error handling, guard statements, availability checks, and more ...