Java Reference
In-Depth Information
C H A P T E R 1 5
Generics and Regular Expressions
Readers who already know Java may very well ask why these two topics are together in the same chapter.
The answer is that they both involve pattern matching. A generic specifier (also known as a parameter) is
a pattern that code must match in order to use a particular block of code (which might be an interface, a
class, a method, or other things). Regular Expressions, on the other hand, use patterns to select
substrings within strings. In both cases, the pattern restricts the available selections. Both have
additional benefits as well, which we'll get to next.
Generics
Generics offer a way to specify the kind of objects that a class, variable, or method can use. The most
common use of generics is to specify what kind of object can go into a collection (such as a list or a tree
or a hashmap). Another use is to allow a type that has yet to be specified to be used where the generic is
specified. In that sense, the type is generic, which is where the name of this idea comes from. We'll see
examples of both kinds of generics as proceed through this section.
Prior to Java 5, Java had no mechanism for specifying generics. That lack led to a number of
problems, including being able to assign unexpected types of objects to a collection (leading to run-time
errors), the necessity of casting objects from one type to another, and overly verbose and complex code.
Fortunately, we now have a way to avoid those problems.
The syntax of generic specifiers relies on the angle bracket characters (< and >). To create a
collection with a generic specifier, add the generic expression at the end of the type specifier for the
collection, as shown in Listing 15-1.
Listing 15-1. A Simple Generic
LinkedList<JPanel> panelList = new LinkedList<JPanel>();
That line of code declares a LinkedList that can only contain JPanel objects. Java 7 introduces a nice
shorthand that slightly reduces the amount of code. In particular, you can leave out the type declaration
when creating an instance of a parameterized object, provided the compiler can infer the type from
elsewhere in the line. Thus, the code in Listing 15-1 could be replaced with the code in Listing 15-2.
Search WWH ::




Custom Search