Java generic programming most summed up __ other

Source: Internet
Author: User

JAVA Generic Programming Notes 1 Introduction

Java generic programming is introduced after the JDK1.5 version. Generics allow programmers to use type abstractions, which are typically used in collections. The following is an example of no generics:

If Foo is a subtype of Bar, and G is a type with a generic type, then g<foo> is not a subtype of g<bar>. This is perhaps the most confusing point in generics learning.

? Extends Object heavy on the specified receive can be a subtype direct? represents receiving any type (not add)

? The type of the super string heavy in Add is a String class or itself

Note the format of the generic method (the generic is the parameter of the method), and the type parameter <T> needs to be placed before the function return value. The generic arguments can then be used in parameters and return values.

In <>, the generic can be any letter (<T>), the same functionality as the question mark (generic class <?>) (wildcard), and <t> without a specific generic class (List,conllection);

Other reading and writing is the same as the difference

Public abstract class Packetprocesser<p extends Papacket,t extends answer> Java code List myintlist=new LinkedList () ; 1 Myintlist.add (Newinteger (0)); 2 integer x= (integer) Myintlist.iterator (). Next (); 3

Note that the 3rd line of code, but this is a very unpleasant point, because the programmer must know that they are stored in the list of the object type is integer, but in the return of the elements in the lists, or must cast the type, this is why. The reason is that the compiler can only guarantee that the next () method of the iterator returns objects of type object and must be cast in order to guarantee the type safety of the integer variable.

This transformation is not only confusing, it is more likely to cause type conversion exception classcastexception, run-time exceptions are often difficult to detect. Ensure that the elements in the list are of a specific data type, so that you can cancel the type conversion and reduce the chance of error, which is the original purpose of the generic design. Here is an example of using generics:

Java code list<integer> myintlist=newlinkedlist<integer> (); 1 ' myintlist.add (Newinteger (0)); 2 ' Integerx=myintlist.iterator (). Next (); 3 '

In line 1th, specify that the object type stored in the list is an integer so that when you get the objects in the list, you do not have to cast the type.

2 define a simple generic

Here is a definition of the interface list and iterator from the Java.util package, which uses generic techniques.

Java code public interface list<e> {<span style= "white-space:pre;"   > </span>void Add (E x); <span style= "WHITE-SPACE:PRE;"   > </span>Iterator<E> iterator (); Public interface Iterator<e> {<span style= "white-space:pre;"   > </span>e next (); <span style= "WHITE-SPACE:PRE;"   > </span>boolean hasnext (); }

This is no different from the native type, except that an angle bracket is added to the interface, which is a type parameter (defined as a formatted type parameter that replaces the type with a specific type when called).

You might think so.,list<integer> indicates that the type parameter E in the list is replaced with Integer.

Java code public interface Integerlist {<span style= "white-space:pre;" > </span>void Add (Integer x) <span style= "WHITE-SPACE:PRE;"   > </span>Iterator<Integer> iterator (); }

        type erasure refers to a combination of type parameters that associates a generic type instance to the same byte code. The compiler generates only one byte code for the generic type and associates its instance to this byte code, so the static variable in the generic type is shared by all instances. Also, it is important to note that a static method cannot access the type parameters of the generic class, because the class is not yet instantiated, so if the static method requires a generic capability, it must be made a generic method. The key to type erasure is to clear the information about the type parameters from the generic type and, if necessary, add methods for type checking and type conversions . when using generics, any specific type is erased, and the only thing you know is that you are using an object. For example, list<string> and list<integer> is in fact the same type of running. They are erased to their native type, the List . because there is a type erase at compile time, it is not possible to differentiate methods through instances of the same generic class, such as the following example compile-time error, because after type Erasure, two methods are all parameters of the list type, and therefore cannot differentiate methods based on the type of the generic class.

  Java code   /* Causes compile-time errors */     public class  ; erasure{               public void  test (list<string> ls) {                    system.out.println ("Sting");                }                public void test (list<integer> li) {                    system.out.println ("Integer");                }     }     

So there's a problem, since the actual type of information is erased in the method and class at compile time, how do you know the specific type when you return the object? If the string information is erased after the list<string> is compiled, how do you know when the object in the list is stored in the list by an iterator at run time?

Erasing removes type information from the method body, so the problem at run time is the boundary : The location where the object enters and leaves the method, which is where the compiler performs type checking and inserts the transition code at compile time. All actions in generics occur at the boundary: additional compile-time checks are performed on the values passed in, and transitions are inserted into the values passed.

3. Generics and sub-types

For a thorough understanding of generics, here's an example: (Apple is a fruit subclass)

Java code list<apple> apples = new arraylist<apple> (); 1 list<fruit> fruits = apples; 2

The 1th line of code is clearly right, but the 2nd row is right. We know that fruit fruit = new Apple (), which is definitely true, that Apple is definitely fruit, but line 2nd will go wrong at compile time. This will make people more puzzled is an apple is fruit, why a box of apples is not a box of fruit it. In this way, we assume that the 2nd line of code is OK, so we can add strawberries to the fruits using the statement fruits.add (The New Strawberry ()) (Strawberry subclass of Fruit), but in that case, A list loaded with a variety of different types of fruit, which is obviously not possible, because when we take out the list of fruit objects, it is not clear whether the transition to the apple or strawberry.

in general, if Foo It's Bar . the subtype, G is a type with a generic type, then the g<foo> not g<bar> . 's subtype. This is perhaps the most confusing point in generic learning.

4. Wildcard characters 4.1 wildcard characters.

First look at the code that prints all the elements in the collection.

  Java code   //not using generics    void printcollection (collection c)  {                    <span  Style= "white-space: pre;" >    </span>iterator i=c.iterator ();   <span style= " white-space: pre; " >    </span>for  (K=0;k < c.size (); k++)  {   < Span style= "white-space: pre;" >        </span>system.out.println (I.next ());   < Span style= "white-space: pre;" >    </span>}  }    

Java code//using generic void Printcollection (collection<object> c) {for (Object e:c) {System.out.println (e); }   }

It is easy to see that a version that uses generics can only accept collections with type Object types such as arraylist<object> (), and if it is Arraylist<string>, a compile-time error occurs. Because we said earlier that,collection<object> is not a superclass of all collections. And the old version can print any kind of collection, so how to transform the new version so that it can accept all types of collections. This problem can be solved by using wildcard characters. The modified code looks like this:

Java code//use wildcard characters. That represents a collection that can receive any element type as a parameter void Printcollection (collection<?> c) {<span style= "white-space:pre;" > </span>for (Object e:c) {<span style= "white-space:pre;"   > </span>system.out.println (e); <span style= "WHITE-SPACE:PRE;" > </span>}}

Wildcard characters are used here. Specifies that any type of collection can be used as a parameter. The read element is represented using the object type, which is safe because all classes are subclasses of object. Another problem arises here, as shown in the following code, if you try to use a wildcard character. , an error occurs at compile time when the object is added to the collection. It should be noted that no matter what type of object is added there will be an error. This is because of the wildcard character. Represents an unknown element type that is stored by the collection, and can be of any type. Adding an element to the collection needs to be a subtype of an unknown element type, and because the collection stores an element type that is unknown, we cannot add any elements to the collection. The only exception is NULL, because NULL is a subtype of all types, so although the element type is unknown, null must be its subtype.

  Java code   

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.