package cn.com; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; //要求:获取字符串数组中最长的元素 //在这里要利用Collections的另一个max方法 //public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp)*/ //步骤: //1 Arrays.asList()将数组转换为List即将数组转换为了一种集合 //2 利用Collections.max()方法,找出最大值 //3 重点是让容器具有可比性,即实现了Comparator接口。相当于是把这个List集合里的东西扔进了容器里 public class Test2 { public static void main(String[] args) { String[] strArr = new String[] { "cd", "ab", "ddfa", "sd", "zd" }; List<String> list = Arrays.asList(strArr); String maxStr = Collections.max(list, new strSort()); System.out.println("maxStr=" + maxStr); } } class strSort implements Comparator<String> { @Override public int compare(String str1, String str2) { if (str1.length() < str2.length()) { return -1; } if (str1.length() == str2.length()) { return str1.compareTo(str2); } else { return 1; } } }
时间: 2024-10-06 00:59:34