Generics Types generic learning note <three>

zhaozj2021-02-11  251

Generics Types generic study notes Author: ice clouds Time: 2004-02-29 Contact: icecloud (AT) sina.comBlog: http: //icecloud.51.net I am sorry, so long to submit up some Things delay.

8 types of text? (Class literals) as a runtime type mark (Type token)

In 1.5, java.lang.class is a generic, that is, one type parameter T. If string.class, the type is Class . This is the advantage that when you use the reflect, you can get a more accurate category rather than the general Object.

Collection emps = sqlUtility.select (EmployeeInfo.class, "select name, id from emps"); public static Collection select (Class c, String sqlStatement) {Collection result = New ArrayList (); // Run SQL Query Using JDBC for (/ * Traversing ResultSet * /) {T Item = C.NewInstance (); / * SET All Item's Fields Using Reflection * / Result.Add (Item } Return result;

The SELECT method above is suitable for all classes. This eliminates the type conversion.

Note 10: Class is a very useful technique as a running mark. This technology is widely used in the new Annotation API.

Original: This Technique of Using Class Literals As Run Time Type Tokens Is A Very Useful Trick To Know. It is buy extensively in the New Apis for manipulating annotations.

9 Tongcaver more role

Look at the example below

Public Interface Sink {Flush (T T); PUBLIC Static T Writeall (Collection COLL, SINK SINK) {t Last; for (t t: coll) {Last = T; SNK.FLUSH (Last);} Return Last;} SINK S; Collection CS; String Str = WriteAll (CS, S); // illegal call

Due to the call, the compiler cannot determine what type of is, String is still Object, so it will be wrong. According to the previous knowledge, you can use the wildcard type as follows:

Public Static T Writeall (Collection SINK) SINK S; Collection CS; String Str = WriteAll (CS, S); // Calling legal, but The return value is Object , according to Sink , T is the object type, and the returned T cannot be secure to the String type.

At this time, another wildcard type is introduced: Lower Bound: .

Public Static T Writeall (Collection COLL, SINK SINK) STRING STR = WriteAll (CS, S); // OK

Note 11: The lower limit wildcard? Super T indicates that an unknown type is a super type of t, as if EXTENDS T indicates that the unknown type is the subtype of t.

Original: The solution is to use a form of lower bounded wildcard The syntax super T denotes an unkmown type that is supertype of T. it is the twin of the bounded wildcard we use extends T to denote an unknown type that is a.?? Subtype OF T.

An example will be held after the article is a method of comparing the elements in Collection. For example, in the Treeset, a Compare should be provided to compare the order of elements in the TreeSet. And accepted in the constructor.

Public Interface Comparator {Int Compareto (T FST, T SND);} Treeset (Comparator c);

We provide Compare to be normal comparison, however, if companies are provided, it should work properly. Therefore, the Treset constructor should be modified to:

TREESET (COMPARATOR c);

Similarly, in the MAX method in the Collection, a maximum is returned. These elements must implement the Comparable interface. COLLECTION.MAX (Comparable ) should be able to work. For Class Foo Implements Comparable , if Comparable is provided, it should also work. Therefore, the lower limit wildcard is also introduced here.

// T must be a public static Coll) that implements Comparable, COLLECTION COLL); // T should also be able to accept an actual type, so modify to public static T max (Collection COLL); then how to use wildcards correctly?

Note 12: General, if your API uses only the type parameter T as a parameter, it should take advantage of the lower limit wildcard; the opposite, if your API returns T, you should use the upper limit wildcard to give your client more convenient.

Original:. In general if you have an API that only uses a type parameter T as an argument, its uses should take advantage of lower bounded wildcard Conversely, if the API only returns T, you'll give your clients more flexibility by using upper Bounded Wildcards.

Wildcard capture, Wildcard Capture

The following example should have been clearly unforgettable:

Set Unknownset = new hashset (); ... public static void addtoset (set s, t t); addtoset (unknownset, "abc"); // illegal call

Since unknownset is an unknown type, no actual type cannot be accepted. Such as String. Consider the following code:

Class Collections { Public Static Set unmodifiableSet;} set s = collections.unmodifiableSet; // Works!

It seems that this code should not be allowed, but it is legal. This is because the wildcard capture principle.

Note 13: This situation is very frequent, and there is a special rule that allows such code to appear, which proves to be secure: wildcard capture, allowing the compiler to determine the unknown wildcard type as a model method of the type parameter. Wildcard capture only allows those type parameters that appear in the method parameter list.

Original: Because this situation arises relatively frequently, there is a special rule that allows such code under very specific circumstances in which the code can be proven to be safe This rule, known as wildcard capture, allows the compiler to infer the unknown type of. A Wildcard As a Type Argument to a Generic Method. Wildcard Capture Is Only Allowed If The Type Parameter Being Inferred Only Appers Once in The Methods Argument List.10 Converting Old Codes to Vale

This is called generifying. If you want to convert the old code to the model, please consider how to modify it carefully. Such as java.util.collection:

public interface Collection {public boolean containsAll (Collection c); public boolean addAll (Collection c);} public interface Collection {public boolean containsAll (Collection c); public boolean addAll (Collection c); }

This is a type of security, but it is not compatible with an old code. Because the norm code can only accept the e-type Collectioni.

It must be considered that addall can add any subtypes of e. ContainSall also can be able to accept different types, and more.

Section 9 mentioned the max method.

Public Static t max (Collection COLL);

This exists a problem, that is, the old code is unable to match:

Public Static Comparable Max (Collection COLL); // New Public Static Object Max (Collection Coll); // Old

By explicitly declaring a superclass, you can force them to consistent. And, we know that MAX only reads from his input Colelction, so it is suitable for any subclass of T, modified as follows:

PUBLIC Static T Max (Collection COLL);

This situation is relatively rare, but if you design a library, you should be prepared to seriously consider converting them.

Note 14: When converting a set of existing APIs, you must determine that the model API will not excessively restriction, and continue to support the original API. .

Original: When converting existing APIs, you should think carefully to make certain that the generic API is not unduly restrictive and continue to support the original contract of the API Another problem is the need to be careful: covariant return value (covariant returns) . That is, the return value of the refine subclass method. The old code is as follows:

Public class foo {public foo create) {} // factory method} public class bar extends foo {public foo create () {} // actually created BAR}

Consider the advantage of return value coordination:

Public class foo {public foo create) {} // factory method} public class bar extends foo {public bar create () {} // actually created BAR}

Note 13: This feature is not directly supported by JVM, but supported by the compiler.

Original: The JVM Does Not Directly Support overriding of methods with diffrer. This feature is supported by the compiler.

Here I quote a paragraph of my friend udoo as a summary: http://udoo.51.net

The important part of Java 1.5 is generics. The birth of Java Generics is probably related to .NET's persecution, the previous multiple versions have never seen such a large change.

In this strong type of language in Java, Type Casting is a very difficult thing. The compiler can solve some of the compile time, encounter this problem at runtime, is a potential hidden danger. Reflection technology is an important means of solving the flexible configuration of the application, but can only know which class is at runtime, there may be Casting issues.

The purpose of Template technology in C is to provide fast, easy to use toolbox, STL is the technology that C programming must be mastered. Java generics looks very like C template, but through this article we know, Java Generics is more important to type inspection, you can go to the mandatory type conversion that it seems difficult to guess, probably only the program writer, the most clear, this is here what type. Using Java Generics, the program may be more read, which also reduces the risk of running moments, but several concepts and technologies mentioned here are not easy to understand (there are several incorrect errors in the text). THESERVERSIDE.COM has a debate on whether this technology is required, no matter what, give us a means, it is necessary to use it.

After spent 3 days, I spent 1 week before I finished. It's really laborious. Thank you all the way you have been supporting. Any questions are welcome to come to me discussion.

Copyright Notice: This article is completed by ice cloud, started 9CBS, the author retains Chinese copyright. No commercial use is not permitted without permission. Welcome to the reprint, but please keep the article and copyright statement complete. For contact, please send an email: Icecloud (at) sina.com

转载请注明原文地址:https://www.9cbs.com/read-4943.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.043, SQL: 9