目前这个水平,使用一些第三方提供的方法时要看一下源码,看看别人的实现方式是什么,加强学习。
题目:求输入5个数字的最大值和最小值,输出时最小值在前,空格后接最大值。
Java:
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Please enter five numbers:");
List<Integer> list = new ArrayList<Integer>();
for(int i=0;i<5;i++){
list.add(sc.nextInt());
}
System.out.println(Collections.min(list)+" "+Collections.max(list));
}
这其中使用了工具类中的方法:Collections.min()和Collections.max();
这两个方法时Collections中的静态方法,调用后可以直接得到结果。
以前到这里就结束了,只是会使用并得到正确的结果,但是现在要求更进一步。JDK为1.8。
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;
}
其内部使用了迭代器和compareTo()方法;
min()源码:
public static <T extends Object & Comparable<? super T>> T min(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()一样,只是>和<的区别。
再来看看compareTo()方法:Integer对compareTo()方法的实现是:
public int compareTo(Integer anotherInteger) {
return compare(this.value, anotherInteger.value);
}
其中compare()的实现是:
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
(x < y) ? -1 : ((x == y) ? 0 : 1)
这是一个嵌套的三元运算符。一个很简洁的写法,当我们碰到类似的情况也可以采用这种写法,非常有利于代码的简化。