A brief preliminary understanding of generics

Source: Internet
Author: User

Many people have used generics. However, we have been puzzled by generics. For example, we often use arraylist. But he does not know his benefits.

Generic: when we define a method. The parameter to be used can be (1) int, (2) string, (3) array, or (4) an object.

However, we generally do not create such four classes, but the parameter types are different. We will create a method class with an unknown parameter type.

And when we want to use this class method. Directly declare one of the four parameter types. Then pass the parameters directly. For example, the following example.

This is simple application and understanding of generics:
Public class Finder
{
// Declaration of generic methods
Public static int Find <T> (T [] items, T item)
{
For (int I = 0; I <items. Length; I ++)
{
If (items [I]. Equals (item)
{
Return I;
}
}
Return-1;
}
}

// Call a generic Method
Int I = Finder. Find <int> (new int [] {1, 3, 4, 5, 6, 8, 9}, 6 );

 


Excerpted from the crowdsourced Security Testing Program

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.