Public void Show (T-t), what is the function of the generic t before void

Source: Internet
Author: User
Tags modifier

Reprint content, original link: http://www.cnblogs.com/anrainie/archive/2012/03/09/2387272.html


Public <T> This T is a modifier, which means that it is a generic method , just like a static method.

<T> is not a return value, indicating that the passed-in parameter has a generic

public static <T>list<T> Aslist (T...A)

The first representation is a generic method, and the second indicates that the return value is a list type, and that the list has generics and can only store data of type T

examples of use of generic methods:

1 public <T> void Fromarraytocollection (t[] A, collection<t> c) {  
 2 for         (t t:a) {  
 3             c.add (t);  
 4         }  
 5     }  
 6   
 7   
 8 public void Fromarraytocollection (t[] A, collection<t> c) {  
 9         for (T t:a) {  
ten             C.add (t);  
One         }       

The first method is equivalent to declaring a class of type T for the method, and this method does not give an error in any of the classes.

The second method is equivalent to a class that has no declared type T, at which point the generic t must be added to the class, or the method will give an error.

1 package generic;
 2 
 3/**
 4  * Generic method Test
 5  * 
 6  * @author Caiyu
 7  * 
 8
 */9 public class Genmethod {
Ten 
public     static <T> void display (T t) {         System.out.println ( T.getclass ());
14}

First, a generic declaration must precede a value declaration after the method's modifier (public,static,final,abstract, etc.).

Then, as with a generic class, you can declare multiple generics, separated by commas.

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.