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