max 方法一个参数的源码:
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) { Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (next.compareTo(candidate) > 0) candidate = next; } return candidate; }max 方法两个个参数的源码:
@SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) { if (comp==null) return (T)max((Collection) coll); Iterator<? extends T> i = coll.iterator(); T candidate = i.next(); while (i.hasNext()) { T next = i.next(); if (comp.compare(next, candidate) > 0) candidate = next; } return candidate; }
package newFeatures8; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /* Collections.max(coll)方法演示 * 方法定义:注意:方法的参数是Collection<? extends T>接口,也就是说只要是其子类 * public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) * 我不明白为什么泛型限定里要明写extends Object,哈哈,你牛,你就写一个不是Object子类的试试 * 根据元素的自然顺序 返回给定 collection 的最大元素。 */ public class CollectionsDemo { public static void main(String[] args) { maxElementDemo(); } /** * @author ljh * @param nothing * @return void * @since 1.2 * @description */ public static void maxElementDemo(){ // List<String> list=new ArrayList<>(); list.add("abcd");//String类本身就是实现了Comparable接口 list.add("kkkkk"); list.add("z"); list.add("zz1"); list.add("zz"); list.add("qq"); list.add("qq"); list.sort(null);//先进行排序 Collections.sort(list); System.out.println(list); String max=Collections.max(list);//[abcd, kkkkk, qq, qq, z, zz, zz1] System.out.println("max="+max);//max=zz1 System.out.println("---------------------"); //返回指定比较器所定义的最大元素 max=Collections.max(list,new strLenCompartor()); System.out.println("maxLength="+max); /* * 1.8对list 集合新增的方法: * (1:)default void sort(Comparator<? super E> c) * (2:)default void forEach(Consumer<? super T> action) * (3:)default Stream<E> parallelStream() * (4:)default void replaceAll(UnaryOperator<E> operator) * (5:)default boolean removeIf(Predicate<? super E> filter) * (6:)default Spliterator<E> spliterator() * (7:)default Stream<E> stream() */ } /** * * @author ljh * @description 静态内部类</br> * 按照字符串的长度进行排序,如果字符串长度相同按按照名称排序 */ static class strLenCompartor implements Comparator<String>{ @Override public int compare(String s1, String s2) { int num=new Integer(s1.length()).compareTo(new Integer(s2.length())); //当主要条件相同一定要按照次要条件排序 if (num==0) { return s1.compareTo(s2); } return num; } } }