zoukankan      html  css  js  c++  java
  • Java分享笔记:泛型机制的程序演示

     1 package packA;
     2 
     3 import java.util.*;
     4 
     5 public class GenericDemo {
     6     public static void main(String[] args) {
     7         
     8         TreeSet<String> ts = new TreeSet<String>( new LenSort() );    //<String> 泛型
     9         
    10         ts.add("hidwju");
    11         ts.add("kiesk");
    12         ts.add("agueihrprute");
    13         ts.add("ejmmjueloi");
    14         ts.add("hidwdd");
    15         ts.add("hefwju");
    16         ts.add("agueuenerute");
    17         ts.add("keesk");
    18         
    19         Iterator<String> it = ts.iterator();    //在迭代器引用前加入泛型
    20         while( it.hasNext() ) {
    21             
    22             String s = it.next();    //上面在取迭代器时,在引用前加了泛型声明,所以这里不需要强转
    23             sop(s);
    24         }
    25         
    26 
    27     }
    28     
    29     
    30     public static void sop( Object obj ) {
    31         
    32         System.out.println(obj);
    33         System.out.println();
    34     }
    35 }
    36 
    37 class LenSort implements Comparator<String> {    //实现接口Comparator <String>泛型
    38     
    39     public int compare(String o1 , String o2) {
    40         //在函数头部声明了泛型,这里直接将形参定义为String类型即可,避免了在函数内部的向下转型
    41         
    42         int num = new Integer(o1.length()).compareTo( new Integer(o2.length()) );
    43         
    44         if( num==0 )
    45             num = o1.compareTo(o2);
    46         
    47         return num;
    48     }
    49 }

    希望与各位读者相互交流,共同学习进步。

  • 相关阅读:
    立方体的形成
    三维变换
    实现任意元素居中
    多个transform 属性案例
    旋转轴心案例
    codeforces 706B B. Interesting drink(二分)
    codeforces 706A A. Beru-taxi(水题)
    hdu-5831 Rikka with Parenthesis II(贪心)
    hdu-5826 physics(数学)
    hdu-5813 Elegant Construction(贪心)
  • 原文地址:https://www.cnblogs.com/EarthPioneer/p/9349396.html
Copyright © 2011-2022 走看看