Java Important Technology (19) How to use generics generic type

Source: Internet
Author: User

1.1. usage of generics

parameterized types such as the type parameter T in sample<t> can be used to type the parameters of the constructor, the type of the return value of the method, the type of the parameter that paints the method, the type of the property field, and so on.

 Public classGenericparametertest {//parameterized type T, which can be a reference type such as String,integer. Static classSample<t> { PublicSample (T obj) { This. obj =obj;} //the type of the parameterized type as the return value.  PublicT work () {System.out.println ("Work:" + This. obj);return  This. obj;} //the parameterized type as the type of the parameter.  Public voidupdate (T obj) { This. obj =obj;} //the parameterized type as the type of the property. PrivateT obj;}  Public Static voidMain (string[] args) {//correct usage. T is a string. Sample<String> Sample =NewSample<string> ("Hello"); String obj=sample.work (); Sample.update ("World"); obj=sample.work (); System.out.println (obj); //syntax error. Error usage. //sample<int> anothersample = new sample<int> (1);//correct usage. T is an integer.Sample<Integer> anothersample =NewSample<integer> (1); } 

The results of the operation are as follows:

Work:hello

Work:world

World

Java Important Technology (19) How to use generics generic type

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.