Java Generics and Collections covers everything from the mostbasic uses of generics to the strangest corner cases. It teaches youeverything you need to know about the collections libraries, so you'llalways know which collection is appropriate for any given task, andhow to use it.
Philip Wadler is Professor of Theoretical Computer Science at theUniversity of Edinburgh, where his research focuses on the design ofprogramming languages. He is a co-designer of GJ, work thatbecame the basis for generics in Sun's Java 5.0.
\"A brilliant exposition of generics. By far the best book on thetopic, it provides a crystal clear tutorial that starts with thebasics and ends leaving the reader with a deep understanding of boththe use and design of generics.\"Gilad Bracha, Java Generics Lead, Sun Microsystems
Generics provide flexible type safety to your code. They move many common errors from run time to compile-time and provide cleaner, easier-to-write code. Generics also reduce the need for casting with collections and are used heavily in the Java Collections API.
A collection is a single object that manages a group of objects. Objects in the collection are called elements. Various collection types implement standard data structures including stacks, queues, dynamic arrays, and hashes. All the collection objects have been optimized for use in Java applications. Primitives are not allowed in a collection. The Collections API relies heavily on generics for its implementation.
Note: The Collections classes are all stored in the java.util package. The import statements are not shown in the following examples, but the import statements are required for each collection type:
The example below implements the Comparable interface and its compareTo method. Notice that because the interface is designed by using generics, the angle brackets define the class type that is passed into the compareTo method. The if statements are included to demonstrate the comparisons that take place. You can also merely return a result.
When you see the code , read it as \"ofType\"; the declaration above reads as\"Collection of String c.\" The codeusing generics is clearer and safer. We have eliminated an unsafecast and a number of extra parentheses. More importantly, we havemoved part of the specification of the method from a comment to itssignature, so the compiler can verify at compile time that the typeconstraints are not violated at run time. Because the programcompiles without warnings, we can state with certainty that it willnot throw a ClassCastException at run time. The neteffect of using generics, especially in large programs, is improvedreadability and robustness.
While the primary use of generics is collections, there are manyother uses. \"Holder classes,\" such as WeakReferenceand ThreadLocal,have all been generified, that is, they have beenretrofitted to make use of generics. More surprisingly, classClasshas been generified. Class literals now function as typetokens, providing both run-time and compile-time typeinformation. This enables a style of static factories exemplifiedby the getAnnotation method in the new AnnotatedElementinterface:
Generics are implemented by type erasure: generic typeinformation is present only at compile time, after which it iserased by the compiler. The main advantage of this approachis that it provides total interoperability between generic code andlegacy code that uses non-parameterized types (which aretechnically known as raw types). The main disadvantages arethat parameter type information is not available at run time, andthat automatically generated casts may fail when interoperatingwith ill-behaved legacy code. There is, however, a way to achieveguaranteed run-time type safety for generic collections even wheninteroperating with ill-behaved legacy code.
The java.util.Collections class has been outfittedwith wrapper classes that provide guaranteed run-time type safety.They are similar in structure to the synchronized and unmodifiablewrappers. These \"checked collection wrappers\" are very useful fordebugging. Suppose you have a set of strings, s, intowhich some legacy code is mysteriously inserting an integer.Without the wrapper, you will not find out about the problem untilyou read the problem element from the set, and an automaticallygenerated cast to String fails. At this point, it istoo late to determine the source of the problem. If, however, youreplace the declaration:
You should use generics everywhere you can. The extra effort ingenerifying code is well worth the gains in clarity and typesafety. It is straightforward to use a generic library, but itrequires some expertise to write a generic library, or to generifyan existing library. There is one caveat: You may not use generics(or any other Tiger features) if you intend to deploy the compiledcode on a pre-5.0 virtual machine.
If you are familiar with C++'s template mechanism, youmight think that generics are similar, but the similarity issuperficial. Generics do not generate a new class for eachspecialization, nor do they permit \"template metaprogramming.\"
\"A brilliant exposition of generics. By far the best book on thetopic, it provides a crystal clear tutorial that starts with thebasics and ends leaving the reader with a deep understanding of boththe use and design of generics.\" Gilad Bracha, Java Generics Lead, Sun Microsystems
Philip Wadler is a professor of theoretical computer science at the University of Edinburgh, Scotland, where his research focuses on functional and logic programming. He co-authored the Generic Java standard that became the basis for generics in Sun's Java 5.0 and also contributed to the XQuery language standard base. Professor Wadler received his Ph.D., in computer science from Carnegie-Mellon University and co-wrote \"Introduction to Functional Programming\" (Prentice-Hall).
Java Genrics is one of the most important features introduced in Java 5. If you have been working on Java Collections and with version 5 or higher, I am sure that you have used it. Generics in Java with collection classes is very easy but it provides a lot more features than just creating the type of collection. We will try to learn the features of generics in this article. Understanding generics can become confusing sometimes if we go with jargon words, so I would try to keep it simple and easy to understand.
In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap(); is valid.
Java Generic Type Naming convention helps us understanding code easily and having a naming convention is one of the best practices of Java programming language. So generics also comes with its own naming conventions. Usually, type parameter names are single, uppercase letters to make it easily distinguishable from java variables. The most commonly used type parameter names are:
Notice the isEqual method signature showing syntax to use generics type in methods. Also, notice how to use these methods in our java program. We can specify type while calling these methods or we can invoke them like a normal method. Java compiler is smart enough to determine the type of variable to be used, this facility is called type inference.
Suppose we want to add Integers to a list of integers in a method, we can keep the argument type as List but it will be tied up with Integers whereas List and List can also hold integers, so we can use a lower bound wildcard to achieve this. We use generics wildcard () with super keyword and lower bound class to achieve this. We can pass lower bound or any supertype of lower bound as an argument, in this case, java compiler allows to add lower bound object types to the list.
Generics in Java was added to provide type-checking at compile time and it has no use at run time, so java compiler uses type erasure feature to remove all the generics type checking code in byte code and insert type-casting if necessary. Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead. For example, if we have a generic class like below;
gives you error of type mismatch because you are trying to assign a ArrayList of List of object of java class Object to a List that contains the List of any type of objects that are subclass of java class Object.
With the help of generics, while one can implement algorithms Implementing generic algorithms, one can have that work on different types of objects and at the same they are type-safe too.
There has been a lot of excitement in the Java world with the release of Java SE 8. New and updated language features in the release allow developers to be more productive by decreasing the amount of code that needs to be written and by making code easier to use. To fully understand the implementation of some new features, such as lambdas, it is important to understand the core concepts of the language. One such concept that plays an important role in many Java SE 8 features is generics.
This article begins by providing a simple explanation of generics, along with presenting some basic concepts. After taking a look at the basic concepts, we will dive into some scenarios demonstrating the use of generics. Lastly, we will see how generics are an important ingredient for some constructs that are new to Java SE 8. 59ce067264