Generic methods for Java __java

Source: Internet
Author: User

Article reference from: http://www.cnblogs.com/iyangyuan/archive/2013/04/09/3011274.html


There are generic methods and generic classes.

Generics similar to the following code definitions are generic methods:


Package com.test.GenericTest;

Import java.util.ArrayList;
Import java.util.List;

Package com.test.GenericTest;

Import java.util.ArrayList;
Import java.util.List;

public class genericfoo<t>
{
	private T value;

	Public T GetValue ()
	{return
		value;
	}

	public void SetValue (T value)
	{
		this.value = value;
	}
	
	public static void Main (string[] args)
	{
		genericfoo<string> foo1 = new genericfoo<string> ();
		
		list<string>  list = new arraylist<string> ();
		
		
		Foo1.setvalue ("HelloWorld");
		
		System.out.println (Foo1.getvalue ());
		
		
	}



The preceding code defines a genericfoo<string> class.


A generic method that resembles the way defined below


Public <T> t[] ToArray (t[] a) {
        if (A.length < size)
            //Make a new array of A's runtime type, but my cont Ents: Return
            (t[]) arrays.copyof (elementdata, size, A.getclass ());
	System.arraycopy (elementdata, 0, a, 0, size);
        if (a.length > Size)
            a[size] = null;
        return A;
    }

return type t[] must precede <T> declare as generic method.


A generic class that indicates the specific type of a generic when instantiating a class, and a generic method that indicates the specific type of the generic when the method is invoked. Note: The generic method invocation indicates what type of generic t is.

A generic class is such as arraylist<string> list = new ArrayList () that indicates the type of the generic t when the class is initialized. This is the declaration of a generic class.




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.