Java generic learning notes

Source: Internet
Author: User

This article is a Java generic learning note from the Internet. I have extracted some valuable parts that I think have not been sorted out. I will first back up them here.

Http://docs.oracle.com/javase/1.5.0/docs/guide/language/generics.html
Generics are defined in classes, interfaces, and methods. They are used for implementation (extends, implements) and instantiation.

When defining a class or interface, you can use the <E extends fruit> form to perform operations on E in the class.
Use "list <? Extends fruit> "in this form, you can receive the list in this range as a parameter.
During instantiation, you cannot use the question mark (?) to specify the generic type -- not the new list <? Extends Apple> ();
During inheritance or implementation, the question mark cannot be used to specify the generic type. -- public interface mylist extends list cannot be used. <? Extends Apple>

Pecs (producer-extends, consumer-Super) Principles for extends and super keywords:
If the parameterized type represents a t producer, use <? Extends T>, because it can only be get, used to extract data from the producer (as long as the producer can produce a subclass of T, it can certainly produce t );
If the parameterized type represents a t consumer, use <? Super T>, because it can only be added, used to add data to the consumer (as long as the consumer can consume the super class of T, it can certainly consume T ).

Http://www.infoq.com/cn/articles/cf-java-generics

General inheritance principles:

1. The relationship between generic classes with the same type parameters depends on the inheritance architecture of the generic classes. That is, list <string> is the sub-type of collection <string>. List <string> can replace collection <string>. This situation also applies to type declarations with upper and lower bounds.

2. When wildcard is used in the type declaration of a generic class, its Subtypes can be expanded in two dimensions. For example, for collection <? Extends number>, its Subtypes can be expanded in the collection dimension, that is, list <? Extends number> and set <? Extends number> and so on. You can also expand the number hierarchy, that is, collection <double> and collection <integer>. As a result, arraylist <long> and hashset <double> are both collections. <? Child type of extends number>.

3. If a generic class contains multiple type parameters, apply the preceding rules for each type parameter.

Generic definition principles:

1. generic classes are basically the same as general Java classes, but the type parameters declared by <> are added to the class and interface definitions.

2. A class can have multiple type parameters, such as myclass <x, y, z>.

3. You can specify an upper bound when declaring each type parameter.

4. The declared type parameters can be used as the parameters and return values of methods, or as the types of domain and local variables in Java classes.

5. Due to the type erasure mechanism, type parameters cannot be used to create objects or as static variables.

Http://www.ibm.com/developerworks/cn/java/j-jtp01255.html

If there is no backward compatibility concerns, the collection framework will be designed like this (but not actually ):

Interface collection <E> {

Public T [] toarray (class <t super E> elementclass );

}

This is very common. If E is an apple class, the input of any apple parent class (such as fruit) is legal and the fruit array is returned.

If an object is input, it is equivalent to the object [] toarray () method of the current collection interface.

Similarly, if there is no backward compatibility concerns, the remove and removeall of the Collection framework will be written like this (but not actually ):

Interface collection <E> {

Public Boolean remove (E); // not really

Public void removeall (collection <? Extends E> C); // not really

}

The defect is that only compatible types of the current generic type can be passed in, and any object or collection <Object> cannot be passed in. In this way, the existing API definition cannot be compatible.

You cannot create generic objects because the compiler does not know what constructor to call. If a generic class needs to construct an object of the specified type using the generic type parameter, the constructor should accept the class text (FOO. class) and save them to create instances through reflection (similar to the toarray method of the preceding collection)

Http://www.cnblogs.com/stephen-liu74/archive/2012/01/20/2228938.html

Type-safe heterogeneous containers (internal use of Map <class <?>, Object> ):

Public class favorites {

Public <t> void putfavorite (class <t> type, t instance );

Public <t> T getfavorite (class <t> type );

}

For example, columns used for an indefinite number of databases: data of each cell is saved to the container by specifying the type of favorites in this way, and then saved as an element to the upper-layer result container.

Arrays of the generic type cannot be instantiated: new list <string> [3] is invalid.

However, it is valid to forcibly convert an object array to a generic array when the type can be determined. For example, the source code of arraylist is return (T []) arrays. copyof (elementdata, size,. getclass ());

Generic method:

When declaring a method, you can add the required type parameters to the Front (this parameter type does not need to be defined in the class ):

Public static <E> set <E> Union (set <E> S1, set <E> S2 );

Static tool methods are especially suitable for writing in this way.

Http://blog.csdn.net/mai0net/article/details/7320399

Generally, when writing a Java generic method, the return value type and at least one parameter type should be generic, and the type should be consistent. If only the return value type or one of the parameter types uses the generic type, the usage of this generic method is greatly limited, basically to the same level as that of the non-generic method.

First: public static <t extends commonservice> T getservice (class <t> clazz );

Noticeservice = commonservice. getservice (noticeservice. Class); // use the first generic method correctly without compilation errors.

Noticeservice = commonservice. getservice (userservice. Class); // if you use the first generic method incorrectly, a compilation error occurs.

Type 2: public static <t> T getservice (class <? Extends commonservice> clazz );

Noticeservice = commonservice. getservice (noticeservice. Class); // use the second generic method correctly without compilation errors, correct logic, and running exceptions.

Noticeservice = commonservice. getservice (userservice. class); // if the second generic method is used incorrectly, no compilation error will occur, but the logic is incorrect. It is dangerous to run the program!

Many generic descriptions on the Internet are good, but I don't know if it's a JDK version problem. I can't actually compile it, so I had to rewrite and try it myself under jdk1.7, add a summary and a comment as follows:

 
Public Class fruit {}
 
Public class Apple extends fruit {}

Public class basket {// retrieve the fruit from the generic list. The elements in the fruit must be child classes of fruit. Therefore, the public static fruit getfruit (list <? Extends fruit> List) {return list. get (0);} // put apple into a generic list (This list can receive the type of the parent class of apple, so it can certainly receive the subclass of Apple or apple) public static void addapple (list <? Super Apple> list, Apple) {list. Add (Apple );}}

 
Public class generictester extends acttester {public void test1 () {list <Apple> applelist = new arraylist <Apple> (); applelist. add (new Apple (); // first define the list <Apple>, and fill in the element fruit = basket. getfruit (applelist); // list <Apple> type conforms to list <? Requirements for extends fruit>} public void Test2 () {list <fruit> fruitlist = new arraylist <fruit> (); basket. addapple (fruitlist, new Apple (); // list <fruit> compliant with list <? Super Apple> requirements }}

Public class genericcompiletester {public void addinteger1 (list <?> List) {list. add (1); // compilation error. Because the question mark indicates the type of "not sure during compilation, but determined during runtime", integer does not necessarily meet the requirements. In fact, this is equivalent to <? Extends object >}public void addinteger2 (list <Object> List) {list. add (1); // The compilation is successful, because the object type is determined during the compilation and runtime, And the integer must meet the requirements} public void test () {list <string> List = new arraylist <string> (); addinteger2 (list); // compilation error, because list <string> cannot be passed as list <Object>, otherwise, the number 1 is added as a string and the type is no longer secure.} public void test3 () {list <? Extends fruit> fruitlist = new arraylist <Apple> (); fruitlist. add (new Apple (); // compilation error. The compiler cannot determine which subclass of fruit is allowed by list. add (new fruit (); // compilation error. The compiler cannot determine which subclass of fruit is allowed by list} public void test4 () {list <? Super Apple> fruitlist = new arraylist <fruit> (); fruitlist. add (new Apple (); // After compilation, both Apple and Apple sub-classes can ensure the fruitlist meets the condition requirements. add (new fruit (); // compilation error. The compiler cannot determine which level of parent class or interface the list allows Apple }}

Related Article

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.