Java generic programming and java generic programming

Source: Internet
Author: User
Tags union of sets

Java generic programming and java generic programming
General classes and methods are for specific data types. When writing a class and method suitable for multiple data types, generic programming is required, java generic programming is similar to a template in C ++, that is, a parameterized programming method. Specifically, it abstracts information related to data types, it mainly provides general implementation and logic, and the information related to the data type is determined by the time-in-use parameters.

 

I. generic classes:
  • Stack implementation

Sample Code:

Package com. genericity; import org. junit. test;/*** @ Title: publish liststack. java * @ Package com. genericity * @ Description: compile a generic stack (Linked List) * @ author lky * @ date 8:34:07 on January 1, October 17, 2015 * @ version V1.0 */public class initialize liststack <T> {/*** @ Title: publish liststack. java * @ Package com. genericity * @ Description: defines the node type in the stack * @ author lky * @ date 8:38:51 on January 1, October 17, 2015 * @ version V1.0 */private static class No De <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;} boolean isEmpty () {return item = null & next = null;} private Node <T> top = new Node <T> (); // stack top pointer public void push (T item) {// top = new Node in the stack <T> (item, top);} public T pop () {// output stack T result = top. item; if (! Top. isEmpty () {top = top. next;} return result ;}}

Test:

package com.genericity;import org.junit.Test;public class testLinkedListStack {    @Test    public void testPush(){        LinkedListStack<String> aLinkedListStack=new LinkedListStack<String>();        aLinkedListStack.push("lky");        aLinkedListStack.push("aaaa");        String res=aLinkedListStack.pop();        while(res!=null){            System.out.println(res);            res=aLinkedListStack.pop();        }    }}
Ii. Generic method:
Package com. genericity; import java. util. arrayList; import java. util. date; import org. junit. test; public class GenericMethods {/*** @ Title: getType * @ Description: return the Data Type of any array * @ param item */public <T> String getType (T item) {return item. getClass (). getName () ;}@ Test public void test () {System. out. println (new GenericMethods (). getType (new Date (); System. out. println (new GenericMethods (). getType (1); System. out. println (new GenericMethods (). getType ("lky"); System. out. println (new GenericMethods (). getType (new ArrayList <String> ()));}}
Iii. Generic set:

In view of the above problems, Java 5 introduces a generic mechanism to explicitly specify the Data Type of its elements when defining a collection container object. When using a collection container, the compiler checks whether the data type matches the data type specified by the container. If the data type does not match the data type, the compiler enforces the data type security.

Sample Code:

package com.genericity;import java.util.ArrayList;import java.util.HashMap;import java.util.HashSet;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.Queue;import java.util.Set;import org.junit.Test;public class New {    public <k, v> Map<k, v> map() {        return new HashMap<k, v>();    }    public <T> List<T> list() {        return new ArrayList<T>();    }    public <T> LinkedList<T> linkList() {        return new LinkedList<T>();    }    public <T> Set<T> set() {        return new HashSet<T>();    }    public <T> Queue<T> queue() {        return new LinkedList<T>();    }        @Test    public void test(){        New new1=new New();        Map<String, LinkedList<String>> lisMap=new1.map();    }}
  • Integration of Mathematics

Code implementation:

Package com. genericity; import java. util. hashSet; import java. util. set; import org. junit. test; public class Sets {/*** @ Title: union * @ Description: union of sets * @ throws */public static <T> Set <T> union (Set <T> a, Set <T> B) {Set <T> set = new HashSet <T> (a); set. addAll (B); return set;}/*** @ Title: intersetion * @ Description: set intersection */public static <T> Set <T> intersetion (Set <T> a, Set <T> B) {Set <T> set = new HashSet <T> (a); set. retainAll (B); return set;}/*** @ Title: difference * @ Description: set difference Set */public static <T> Set <T> difference (Set <T> a, Set <T> B) {Set <T> set = new HashSet <T> (a); set. removeAll (B); return set;} public static <T> Set <T> complement (Set <T> a, Set <T> B) {return difference (union (, b), intersetion (a, B) ;}@ Test public void test () {HashSet <Integer> a = new HashSet <Integer> (); hashSet <Integer> B = new HashSet <Integer> (); for (int I = 0; I <8; ++ I) {if (I <5). 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 ());}}
Iv. Upper boundaries of generic boundaries:
  • In Java generic programming, the extends keyword is used to specify the upper boundary of the generic parameter type, that is, the generic type can only be applied to the subtype of the extends keyword or interface.
  • Java generic programming can have multiple boundaries and can be declared using the <T extends A & B & C> syntax. Only one of them can be A class, in addition, it can only be the first one behind extends as a class, and the others can only be interfaces (different from the extends in the class/interface ).
  • After the generic boundary is used, the generic object can use the common member variables and methods in the boundary object.
Bottom Border:
  • T Super A limits that the telement can only be the parent class of.
5. wildcard characters
  • Wildcard "?"

An example of a classic wildcard is as follows:

Public class SampleClass <T extends S> {...}

Suppose A, B, C ,... Z all 26 classes implement the S interface. We need to use these 26 class-type generic parameters. What should I do during the instantiation? Write down

SampleClass <A> a = new SampleClass ();

SampleClass <B> a = new SampleClass ();

...

SampleClass <Z> a = new SampleClass ();

This is obviously redundant. It is better to use objects instead of generics. It is very convenient to use wildcards:

SampleClass <? Extends S> SC = newSampleClass (); 6. borderless wildcard

  • Wildcard wildcards can also not specify boundaries. Non-boundary wildcards mean the types of uncertain parameters. during compilation, generic wildcards divide the type information and are considered to be of the Object type.
  • List and List <?> The difference is that List is an original type List, which can store any Object type objects without the need for type check during compilation. List <?> It is equivalent to List <Object>. It is not a List of the original type. It stores some specific types, but is not sure about the type yet. It requires a type check during compilation. Therefore, List is more efficient than List <?> High.
  • See http://blog.csdn.net/chjttony/article/details/6801406 for details

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.