Getting Started with Java-generics (i)

Source: Internet
Author: User

Getting Started with Java-generics (i)

Generic programming means that the code you write can be reused by many different types of objects, and more importantly, it guarantees the security of the data type. But designing generics is not that easy, and what a generic programmer has to do is predict all the possible uses of all classes in the future.

One: Target

Generic programming is divided into 3 tiers, with the basic level being the use of generics-a collection of typical small ArrayList-without regard to how and why they work. Most program apes will stay on this level until there is a problem.

II: Simple Generic class
Package Sep22;public class Pair<t> {//generics can have multiple variables, such as the public class Pair<t,k>{}private T first;//t type variable private t SECOND;//T type of variable public Pair () {//constructor first=null;second=null;} Public Pair (T first,t second) {//constructor overwrite This.first=first;this.second=second;} Public T GetFirst () {return first;} public void Setfirst (T first) {This.first = first;} Public T Getsecond () {return second;} public void Setsecond (T second) {this.second = second;}}

You can then instantiate the object by substituting the type variable with the specific type, for this example:

  

Pair<string>

  

After instantiating an object, you can think of the constructor as a normal class constructor:

Pair<string> () pair<string> (String first,string Second)

and methods

String GetFirst () string Getsecond () void Setfirst (string) void Setsecond (String)
Three: Generic methods

Generics can also define generic methods in a normal class

Class arrayalg{public    static <T> t Getmiddle (t ... a) {        return A[A.LENGTH/2];}}

  

Congo says
    1. A generic class is a factory of ordinary class that produces classes of the corresponding type when instantiating an object.

Getting Started with Java-generics (i)

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.