Easy understanding of Java generics

Source: Internet
Author: User
Diagnose Java code: Easy To Understand Java generics

Generic Guidelines for Java tiger versions and JSR-14 prototype Compilers

Level: elementary

Eric E. Allen (eallen@cs.rice.edu), PhD student, Rice University Java programming language team

May 14, 2003

Of this monthDiagnose Java codeThis section describes generic types and their supported features. The tiger to be released by the end of 2003, that is, Java v1.5, intends to include these generic types and features. Eric Allen provides code samples, these samples illustrate the advantages and disadvantages of generic types by focusing on tiger features such as basic type restrictions, restricted generics, and polymorphism methods (other features will be discussed in the upcoming column, for example, the specific performance of the generic type in tiger and the generic type that may be extended beyond Tiger ). ClickDiscussionGo to the Forum and share your experiences with the author and other readers.

J2se 1.5-code: Tiger-planned to be released by the end of 2003. I have always been keen to collect as much information as possible about the coming new technologies, so I will write a series of articles to discuss new and restructured features that can be obtained from v1.5, this is the first article. I particularly want to talk about generic types and focus on the changes and adjustments made to support them in tiger.

In many ways, tiger must be the greatest progress made so far in Java programming, including significant extensions to the source language syntax. The most significant change planned in tiger is to add generic types, as shown in advance in the JSR-14 prototype Compiler (you can download the compiler for free now; see references ).

Let's start with introducing what generic types are and what features are added to support them.

Data type conversion and error

To understand why generic types are so useful, we need to focus on one of the most common causes of errors in the Java language-the need to constantly convert expressions to downcast) it is a more specific data type than its static type (see the "the double descent bug pattern" in reference to learn about the data type conversion, some problems that may be encountered ).

For each downward type conversion in the programClassCastExceptionIt is a potential danger and should be avoided as much as possible. But they are usually unavoidable in the Java language, even in well-designed programs.

The most common reason for downward type conversion in Java is that classes are often used in a dedicated way, which limits the possible runtime types of parameters returned by method calls. For example, assume thatHashtableAdd and retrieve elements from. In a given program, the element type used as the key and the Value Type stored in the hash table cannot be any object. Generally, all keys are instances of a specific type. Similarly, the stored values share a ratioObjectMore specific public types.

However, in the current Java language version, it is impossible to declare the specific keys and elements of the hash tableObjectMore specific types. The Type feature characters that perform the insert and search operations on the hash table tell us that only any objects can be inserted and deleted. For example,putAndgetThe operations are described as follows:

Listing 1. Description of the insert/search type indicates that the object can only be any one.

class Hashtable {
Object put(Object key, Object value) {...}
Object get(Object key) {...}
...
}

Therefore, when weHashtableFor example, even if we know thatHashtableOnlyStringThe type system only knows that the retrieved value isObjectType. The retrieved value is specificStringMust be forcibly convertedString, Even if the retrieved element is added to the same code block, this is also true!

Listing 2. Forcibly convert the retrieved value to a string

import java.util.Hashtable;
class Test {
public static void main(String[] args) {
Hashtable h = new Hashtable();
h.put(new Integer(0), "value");
String s = (String)h.get(new Integer(0));
System.out.println(s);
}
}

Note:mainThe data type to be converted in the third row of the method body. Because the Java type system is quite weak, the code will be exposed due to data type conversion like above. These data type conversions not only make Java code more lengthy, but also reduce the value of static type checks (because each data type conversion is a pseudo command that chooses to ignore static type checks ). How can we extend this type of system without having to avoid it?



Back to Top

Use the generic type to solve the problem!

To eliminate the data type conversion mentioned above, a common method is to useGeneric TypeTo increase the Java type system. Generic types can be considered as type "functions". They are parameterized by type variables. These types of variables can be performed by using various types of parameters according to the context.Instantiation.

For exampleHashtableDifferent, we can define generic classesHashtable<Key, Value>, WhereKeyAndValueYes. In addition to a series of type parameter declarations enclosed by Angle brackets after the class name, the syntax for defining such generic classes in tiger is similar to that for defining common classes. For example, you can define your own generic type as follows:HashtableClass:

Listing 3. Defining the generic hashtable class

class Hashtable<Key, Value> { ... }

You can then reference these type parameters, as we reference the common type in the class definition subject, as shown below:

Listing 4. Reference a type parameter just like a common type

class Hashtable<Key, Value> {
...
Value put(Key k, Value v) {...}
Value get(Key k) {...}
}

The scope of the type parameter is the subject part of the corresponding class definition (except for static members) (in the next article, we will discuss why tiger implementation has such a "strange experience ", this restriction must be applied to static members. Please note !).

Create a newHashtableYou must pass the type parameter to specifyKeyAndValue. The method for passing type parameters depends on how we plan to useHashtable. In the above example, what we really want to do is createHashtableInstance, it onlyIntegerIngString. You can use the newHashtableClass to complete this task:

Listing 5. Creating an instance that maps Integers to strings

import java.util.Hashtable;
class Test {
public static void main(String[] args) {
Hashtable<Integer, String> h = new Hashtable<Integer, String>();
h.put(new Integer(0), "value");
...
}
}

Data type conversion is no longer required. Note that this parameter is used to instantiate a generic class.Hashtable. Just as the type parameters of a generic type are enclosed in angle brackets, parameters of a generic type application are also enclosed in angle brackets.

Listing 6. Remove unnecessary data type conversions

...
String s = h.get("key");
System.out.println(s);

Of course, if programmers only need to redefine all standard utility classes to be able to use generic types (suchHashtableAndList), It may be a huge project. Fortunately, Tiger provides users with generic versions of all Java Collection classes, so we don't have to redefine them by ourselves. In addition, these classes can work seamlessly with the old Code and the new generic code (next month, we will explain how to do this ).



Back to Top

Restrictions on the basic types of Tiger

One of the limitations of type variables in tiger is that they must be instantiated using the reference type-the basic type does not work. Therefore, in the preceding exampleintMapStringOfHashtable.

This is a pity, because it means that as long as you want to use basic types as generic type parameters, you must assemble them as objects. On the other hand, the current situation is the worst; you cannotintPassed as a keyHashtableBecause all keys must beObjectType.

What we really want to see is that the basic types can be automatically packaged (boxing) and unboxing, similar to the operations performed with C # (or better than the latter ). Unfortunately, tiger does not plan to include automatic packaging of the basic type (but people can always expect this feature to appear in Java 1.6 !).



Back to Top

Restricted Generic

Sometimes we want to restrict the possible type instantiation of generic classes. In the above exampleHashtableCan be instantiated using any type parameter we want to use, but for some other classes, we may want to limit the possible type parameter set to a given typeRange.

For example, we may want to define a genericScrollPaneClass, which references commonPane. IncludedPaneThe runtime type of is usually a classPaneBut the static type is onlyPane.

Sometimes we want to use getter to retrieve the containedPaneBut it is expected that the getter return type should be as specific as possible. We may want to set the type parameterMyPaneAddScrollPane.PaneAny subclass. Then, you can use the following clauses:extends Bound To describeMyPaneTo setMyPaneScope:

Listing 7. Using the extends clause to describe the mypane Declaration

class ScrollPane<MyPane extends Pane> { ... }

Of course, we can avoid using explicit ranges at all, as long as we can ensure that we do not use inappropriate types to instantiate type parameters.

Why is it difficult to set a range for type parameters? There are two reasons. First, the range adds the static type check function. With the static type check, you can ensure that each instantiation of the generic type meets the Set range.

Secondly, because we know that each instantiation of A type parameter is a subclass within this range, we can safely call any method within this range for the type parameter instance. If no explicit range is set for the parameter, the default range isObject, Which means we cannot call the range instance inObjectAny method that does not appear in.



Back to Top

Polymorphism Method

In addition to using type parameters to parameterize classes, using type parameters to parameterize methods is often equally useful. In generic Java programming terms, the method of parameterization by type is calledPolymorphic Method).

The reason why the polymorphism method is useful is that sometimes, in some operations we want to execute, the type correlation between parameters and returned values is originally generic, however, this generic nature does not depend on any class-level type information and is different for each method call.

For example, assume that you wantfactoryAdd methodListClass. This static method only includes one parameter and will also be the unique element of the List (until other elements are added ). Because we hopeListIt becomes the generic type of the element type it contains, so it is expected to be staticfactoryMethod with Type VariableTThis parameter is returned.List<T>.

But we do want this type of VariableTCan be declared at the method level, because it will change with each separate method call (and, as I will discuss in the next article, tiger's "weird practices" stipulate that static members are not within the scope of class-level parameters ). Tiger allows us to declare a type parameter at a separate method level by using the type parameter as the prefix of the method declaration. For examplefactoryMethodmakeAdd prefix:

Listing 8. Add the type parameter as the prefix to the method declaration

class Utilities {
<T extends Object> public static List<T> make(T first) {
return new List<T>(first);
}
}

In addition to the flexibility added in the polymorphism method, Tiger also adds an advantage. Tiger uses the type inference mechanism to automatically deduce the type of the polymorphism Method Based on the parameter type. This can greatly reduce the complexity and complexity of method calls. For example, if you want to callmakeMethod to Construct the includenew Integer(0)OfList<Integer>For new instances, you only need to write:

Listing 9. Force make to create a new instance

Utilities.make(Integer(0))

The instantiation of the type parameter is automatically deduced from the method parameter.


Conclusion

As we have seen, adding generic types to the Java language will greatly enhance our ability to use static type systems. Learning how to use generic types is quite simple, but you also need to avoid some defects. In the following article, we will discuss how to make full use of the specific performance of the generic type that will appear in tiger, as well as some defects. We will also study the extension of generic Java tools. We hope these tools will appear on the Java platform that is still in the design stage.

From http://www.ibm.com/developerworks/cn/java/j-djc02113/

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.