求一组数中的最大最小数以及源码分析

目前这个水平,使用一些第三方提供的方法时要看一下源码,看看别人的实现方式是什么,加强学习。

题目:求输入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)
这是一个嵌套的三元运算符。一个很简洁的写法,当我们碰到类似的情况也可以采用这种写法,非常有利于代码的简化。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值