Java generics: Generic classes, generic interfaces, and generic methods

Source: Internet
Author: User

Source: 1190000002646193

Generic class

 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; }}

Generic interface

 Public Interface Generator<t> {    public  T Next ();}
 Public class Implements Generator<string> {    privatenew string[]{"Apple", "Banana", "Pear"};    @Override    public  String Next () {        new  Random ();         return fruits[rand.nextint (3)];}    }

Generic methods (a basic principle: use generic methods as much as possible )

     Public Static void out (T-t) {        System.out.println (t);    }

Type wildcard character (in common method, used when no generic method is used)

Upper limit: <? Extends T>? is a subclass of T and T

Lower limit: <? Super T>? is the parent class of T and T

Java generics: Generic classes, generic interfaces, and generic methods

Related Article

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.