- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- public static void main(String[] args)
- {
- //建立一个字符串集合
- List<String> list = new ArrayList<String>();
- //添加字符串
- list.add("qbcdef");
- list.add("cef");
- list.add("af");
- list.add("ab");
- list.add("wbf");
- list.add("b");
- list.add("k");
- maxLenDemo(list);//最大长度字符串
- }
- //获取最长字符串
- public static void maxLenDemo(List<String> list)
- {
- sop(list);
- //获取长度最大字符串
- String max = Collections.max(list,new StrLenComparator());
- //打印max
- sop("max="+max);
- }
- //构造字符串长度比较器
- class StrLenComparator implements Comparator<String>
- {
- public int compare(String str1 ,String str2)
- {
- int num = new Integer(str1.length()).compareTo(new Integer(str2.length()));
- if(num == 0)
- return str1.compareTo(str2);
- return num;
- }
- }
复制代码
|
|