本文为大家分享了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