黑马程序员技术交流社区

标题: 集合框架工具类-最大长度字符串 [打印本页]

作者: itheima_llt    时间: 2015-4-22 00:29
标题: 集合框架工具类-最大长度字符串
  1.         public static void sop(Object obj)
  2.         {
  3.                 System.out.println(obj);
  4.         }

  5.         public static void main(String[] args)
  6.         {
  7.                 //建立一个字符串集合
  8.                 List<String> list = new ArrayList<String>();

  9.                 //添加字符串
  10.                 list.add("qbcdef");
  11.                 list.add("cef");
  12.                 list.add("af");
  13.                 list.add("ab");
  14.                 list.add("wbf");
  15.                 list.add("b");
  16.                 list.add("k");
  17.                 maxLenDemo(list);//最大长度字符串
  18. }
  19.         //获取最长字符串
  20.         public static void maxLenDemo(List<String> list)
  21.         {
  22.                 sop(list);
  23.                 //获取长度最大字符串
  24.                 String max = Collections.max(list,new StrLenComparator());
  25.                 //打印max
  26.                 sop("max="+max);       
  27.         }
  28. //构造字符串长度比较器
  29. class StrLenComparator implements Comparator<String>
  30. {
  31.         public int compare(String str1 ,String str2)
  32.         {
  33.                 int num = new Integer(str1.length()).compareTo(new Integer(str2.length()));
  34.                 if(num == 0)
  35.                         return str1.compareTo(str2);
  36.                 return num;
  37.         }
  38. }
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2