L--java generics, generic classes, generic interfaces, and generic methods

Source: Internet
Author: User
Tags pear

Brief introduction

The motivation for generics to occur is: In order to create a container class

Generic class

The container class should be one of the most reusable class libraries. Let's take a look at how a container class is defined without a generic type:

 Public classContainer {PrivateString Key; PrivateString value;  PublicContainer (String k,string v) {key=K; Value=v; }     PublicString GetKey () {returnkey; }     Public voidSetkey (String key) { This. Key =key; }     PublicString GetValue () {returnvalue; }     Public voidSetValue (String value) { This. Value =value; }}

The container class holds a pair of Key-value key-value pairs, but the type is dead, saying that if I want to create a key-value pair that is String-integer type, the current container cannot do it and must be customized. So this obviously reusability is very low.

Of course, you can use object instead of string, and we can only do that before javaSE5, because object is a base class of all types, so it could be transformed directly. However, this flexibility is not enough because the type is still specified, except for the type level specified this time

Higher, is it possible not to specify a type? Is it possible to know what the specific type is at run time?

So, a generic is present.

 Public classContainer<k,v> {    PrivateK Key; PrivateV value;  PublicContainer (K k,v V) {key=K; Value=v; }     PublicK GetKey () {returnkey; }     Public voidSetkey (K key) { This. Key =key; }     PublicV GetValue () {returnvalue; }     Public voidSetValue (V value) { This. Value =value; }}

At compile time, it is impossible to know what type K and V are, but only when the runtime actually constructs and allocates memory based on the type. You can look at the current container class for different types of support:

 Public classmain{ Public Static voidMain (string[] args) {Container<string string> C1 =NewContainer<string, string> ("name", "Gudoumaoning"); Container<string integer> C1 =NewContainer<string, Integer> ("Age", "24"); Container<double double> C1 =NewContainer<double, integer> (1.2, 1.3); System.out.println (C1.getkey ()+ ":" +C1.getvalue ()); System.out.println (C2.getkey ()+ ":" +C2.getvalue ()); System.out.println (C3.getkey ()+ ":" +C3.getvalue ()); } }
Output:
Name:gudoumaoning
Age:24
1.2:1.3
Generic interface

In a generic structure, the generator is a good understanding, see the following builder interface definition:

 Public Interface Generator<t> {    public  T Next ();}
Then define a generator class to implement this interface:
 Public class Implements Generator<string> {    privatenew string[] {"Apple", "banana", "pear"};    @Override    public  String Next () {        new  Random ();         return fruits[rand.nextint (3)];}    }

Call:

 Public class Main {    publicstaticvoid  main (string[] args) {        new fruitegenerator ();        System.out.println (Fruitegenerator.next ());        System.out.println (Fruitegenerator.next ());        System.out.println (Fruitegenerator.next ());        System.out.println (Fruitegenerator.next ());}    }
Output:
Apple
Pear
Pear
Banana
Generic methods

The basic principle is that whenever you can do it, you try to use a generic method. That is, if a generic method can supersede the generalization of the entire class, then the generic method should be limited. Here's a simple definition of a generic method:

 Public class Main {    publicstaticvoid  -out (T-t) {        System.out.println (t);    }     publicstaticvoid  main (string[] args) {        out ("gudoumaoning" );        Out (123);        Out (11.11);        Out (false);}    }
You can see that the parameters of the method are thoroughly generalized, and this process involves the compiler's type deduction and automatic packaging, which means that the original needs our own judgment and processing of the type, and now the compiler helps us. This greatly increases the flexibility of programming by not having to consider which types of parameters to handle later in the process of defining the method. Let's look at an example of a generic and variable parameter:
 Public class Main {    publicstaticvoid  out (t ... args) {        for  (T t : args) {            System.out.println (t);        }            }      Public Static void Main (string[] args) {        out (false);    }}

The output is the same as the previous piece of code, and you can see that generics can be perfectly combined with variable parameters.

L--java generics, generic classes, generic interfaces, and generic methods

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.