Methods with generic Declarations lecturer: Wang Shaohua QQ Group: 483773664 Learning Objectives:
Mastering the definition of generic methods
Mastering the use of generic methods
First, the demand
Suppose you need to implement a method that is responsible for adding all elements of an object array to a collection collection.
12345678910 |
/** &n BSP;&NBSP;&NBSP;&NBSP;&NBSP * Add elements from array to Colleciotn * @param array * @param c */ public void fromarraytocollection (object[] array,collection<object> c) { for (Object object:array) { C.add (object); } } |
The method defined above has no problem, the key is the opening of C in the above method, its data type is collection<object>. As described earlier,,collection<object> is not the parent class of the Collection<string> class, so the functionality of this method is very limited. For example, the following will cause a compilation error:
650) this.width=650; "border=" 0 "src=" http://s3.51cto.com/wyfs02/M00/80/3D/wKiom1c78jOjaqRwAAAozreJcbU513.png " data_ue_src= "E:\My knowledge\temp\4ec1990f-6c7d-4c01-84ea-030627aba3cf.png" >
Ii. Generic Methods
Methods can also be generalized, regardless of whether the class defined at this time is generic. A generic parameter can be defined in a generic method, at which point the type of the parameter is the type of the incoming data.
(i), grammar
12 |
修饰符 <T,S> 返回值类型 方法名(形参列表){ } |
The syntax of a generic method differs from the syntax of a normal method in that it has a type parameter declaration, that the type parameter declaration is enclosed in angle brackets, that multiple type parameters are separated by commas, and that all type parameter declarations are placed between the method modifier and the method return value type.
(ii) Reference code
12345678910 |
/** * 将array中的元素添加到colleciotn中 * @param array * @param c */ public <T> void fromArrayToCollection(T[] array,Collection<T> c){ for (T t : array) { c.add(t); } } |
(iii) Testing
123456789101112 |
public class GenericTest {
public static void main(String[] args) {
Needs needs =
new Needs();
String[] names = {
"孙悟空"
,
"猪八戒"
,
"沙悟净"
};
List<String> c =
new ArrayList<String>();
needs.fromArrayToCollection(names, c);
Double[] doubles = {
2.14
,
3.14
};
List<Double> doubleList =
new ArrayList<Double>();
needs.fromArrayToCollection(doubles, doubleList);
}
}
|
Iv. generic method: Static generic method
12 |
public static <T> void show(T t){ } |
Five, learning video URL:
Http://edu.51cto.com/course/course_id-6083.html
From for notes (Wiz)
Learn from teacher Wang Generics (v): Customizing methods with generic declarations