本文為大家分享了java泛型機制的程序演示具體代碼,供大家參考,具體內容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
package packa; import java.util.*; public class genericdemo { public static void main(string[] args) { treeset<string> ts = new treeset<string>( new lensort() ); //<string> 泛型 ts.add( "hidwju" ); ts.add( "kiesk" ); ts.add( "agueihrprute" ); ts.add( "ejmmjueloi" ); ts.add( "hidwdd" ); ts.add( "hefwju" ); ts.add( "agueuenerute" ); ts.add( "keesk" ); iterator<string> it = ts.iterator(); //在迭代器引用前加入泛型 while ( it.hasnext() ) { string s = it.next(); //上面在取迭代器時,在引用前加了泛型聲明,所以這里不需要強轉 sop(s); } } public static void sop( object obj ) { system.out.println(obj); system.out.println(); } } class lensort implements comparator<string> { //實現接口comparator <string>泛型 public int compare(string o1 , string o2) { //在函數頭部聲明了泛型,這里直接將形參定義為string類型即可,避免了在函數內部的向下轉型 int num = new integer(o1.length()).compareto( new integer(o2.length()) ); if ( num== 0 ) num = o1.compareto(o2); return num; } } |
注:希望與各位讀者相互交流,共同學習進步。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/EarthPioneer/p/9349396.html