Java Generic Programming

Source: Internet
Author: User

General classes and methods are for specific data types, when writing a class and method applicable to a variety of data types need to use generic programming, Java generic programming is similar to the template in C + +, that is, a parameterized type of programming method, specifically to the data type related information abstraction, It mainly provides general-purpose implementations and logic, and data-type-related information is determined by the use-time parameters.

A. Generic class:
    • Implementation of the Stack

Example code:

 Packagecom.genericity;Importorg.junit.Test;/*** @Title: Linkedliststack.java * @Package com.genericity * @Description: Write a generic stack (linked list) *@authorlky * @date October 17, 2015 PM 8:34:07 *@versionV1.0*/ Public classLinkedliststack<t> {        /*** @Title: Linkedliststack.java * @Package com.genericity * @Description: Define the node type in the stack *@authorlky * @date October 17, 2015 PM 8:38:51 *@versionV1.0*/    Private Static classNode<u>{U item; Node<U>Next; Node () { This. item=NULL;  This. next=NULL; } Node (U item,node<U>next) {             This. item=item;  This. next=Next; }                BooleanIsEmpty () {returnitem==NULL&& next==NULL; }            }        PrivateNode<t> top=NewNode<t> ();//stack Top pointer         Public voidPush (T Item) {//into the stacktop=NewNode<t>(Item,top); }         PublicT Pop () {//out of the stackT result=Top.item; if(!Top.isempty ()) {Top=Top.next; }        returnresult; }        }

Test:

 Packagecom.genericity;Importorg.junit.Test; Public classTestlinkedliststack {@Test Public voidTestpush () {Linkedliststack<String> alinkedliststack=NewLinkedliststack<string>(); Alinkedliststack.push ("Lky"); Alinkedliststack.push ("AAAA"); String Res=Alinkedliststack.pop ();  while(res!=NULL) {System.out.println (res); Res=Alinkedliststack.pop (); }    }}
Two. Generic method:
 Packagecom.genericity;Importjava.util.ArrayList;Importjava.util.Date;Importorg.junit.Test; Public classGenericmethods {/*** @Title: GetType * @Description: Returns the data type of any array *@paramItem*/     Public<T>String GetType (T item) {returnItem.getclass (). GetName (); } @Test Public voidTest () {System.out.println (NewGenericmethods (). GetType (NewDate ())); System.out.println (NewGenericmethods (). GetType (1)); System.out.println (NewGenericmethods (). GetType ("Lky")); System.out.println (NewGenericmethods (). GetType (NewArraylist<string>())); }}
Three. Generic collection:
    1. The Java container defaults to object type objects, and if a container contains a type object and a B type object, it is easy to create a conversion error if the user confuses the A and B object types, and a type conversion exception occurs.
    2. A type conversion exception can also be generated if the user does not know the data type of the element in the collection container.

In view of the above problems, JAVA5 introduced a generic mechanism that explicitly specifies the data type of its elements when a collection container object is defined, and when the collection container is used, the compiler checks whether the data type matches the data type specified by the container, and enforces the data type security from the compiler level if it does not conform to the failure to compile.

Example code:

 Packagecom.genericity;Importjava.util.ArrayList;ImportJava.util.HashMap;ImportJava.util.HashSet;Importjava.util.LinkedList;Importjava.util.List;ImportJava.util.Map;ImportJava.util.Queue;ImportJava.util.Set;Importorg.junit.Test; Public classNew { Public<k, v> map<k, v>map () {return NewHashmap<k, v>(); }     Public<T> list<t>list () {return NewArraylist<t>(); }     Public<T> linkedlist<t>linklist () {return NewLinkedlist<t>(); }     Public<T> set<t>set () {return NewHashset<t>(); }     Public<T> queue<t>Queue () {return NewLinkedlist<t>(); } @Test Public voidTest () {New New1=NewNew (); Map<string, linkedlist<string>> lismap=New1.map (); }}
    • The realization of the set in mathematics

Code implementation:

 Packagecom.genericity;ImportJava.util.HashSet;ImportJava.util.Set;Importorg.junit.Test; Public classSets {/*** @Title: Union * @Description: Aggregation of the set *@throws     */     Public Static<T> set<t> Union (set<t> a,set<t>b) {Set<T> set=NewHashset<t>(a);        Set.addall (b); returnset; }        /*** @Title: Intersetion * @Description: Set intersection*/     Public Static<T> set<t> intersetion (set<t>a,set<t>b) {Set<T> set=NewHashset<t>(a);        Set.retainall (b); returnset; }    /*** @Title: Difference * @Description: Set difference set*/     Public Static<T> set<t> difference (set<t>a, set<t>b) {Set<T> set=NewHashset<t>(a);        Set.removeall (b); returnset; }         Public Static<T> set<t> Complement (set<t>a,set<t>b) {       returnDifference (Union (A, B), Intersetion (A, b)); } @Test Public voidTest () {HashSet<Integer> a=NewHashset<integer>(); HashSet<Integer> b=NewHashset<integer>();  for(inti=0;i<8;++i) {            if(i<5) A.add (i); if(i>2) B.add (i);        } SYSTEM.OUT.PRINTLN (Union (A, B). ToString ());        SYSTEM.OUT.PRINTLN (Difference (A, B). ToString ());        System.out.println (Intersetion (A, B). ToString ());    SYSTEM.OUT.PRINTLN (Complement (a, B). ToString ()); }    }
Four. Generic boundary-Upper boundary:
    • Java generic programming uses the extends keyword to specify the upper boundary of a generic parameter type, that is, generics can only be applied to subclasses of classes or interfaces after the extends keyword.
    • The boundaries of Java generic programming can be multiple, declared using such <t extends A & B & c> syntax, where only one is a class, and only the first one behind the extends is the class, and the others are only interfaces (and classes/ The extends meaning in the interface is different).
    • After a generic boundary is used, the generic object can use the public member variables and methods in the bounding object.
Bottom boundary:
    • by T Super a restricts the t element to be a parent class only.
Five. Generic wildcard characters
    • Generic wildcard character "?"

An example of a comparison of classic generic wildcard characters is as follows:

public class SampleClass < T extends s> {...}

If A,b,c, ... Z This 26 class implements the S interface. We need to use a generic parameter to these 26 class types. What happens when the instantiation is done? Write down in turn

sampleclass<a> A = new SampleClass ();

Sampleclass<b> a = new SampleClass ();

...

Sampleclass<z> a = new SampleClass ();

This is obviously redundant, rather than using an object instead of generics, which is handy for using wildcard characters:

sampleclass<? Extends s> sc = Newsampleclass (); six. Wildcard with no bounds

    • Generic wildcard characters can also not specify boundaries, wildcard characters without boundaries mean the type of indeterminate parameters, compile-time generic sassafras except type information, considered to be object type
    • The difference between list and list<?> is that list is a list of primitive types that can hold objects of any object type and do not require compile-time type checking. List<?> is equivalent to List<object> it is not a list of the original type, it holds some specific types, but is not yet sure what type it is, and requires compile-time type checking. So list efficiency is higher than list<?>.
    • Detailed explanation See http://blog.csdn.net/chjttony/article/details/6801406

Java Generic Programming

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.