带compareTo java的迭代器

带compareTo java的迭代器,java,compare,comparator,Java,Compare,Comparator,作为一般概念,假设我们有一个compareTo方法,它返回1、0或-1 使用compareTo方法,如何使用迭代器找出数组中的最大值?简单地说: Iterator<E> it = collection.iterator; E max = null; while(it.hasNext()) { if(max == null) { max = it.next(); } else { e = it.next(); if(e.c

作为一般概念,假设我们有一个compareTo方法,它返回1、0或-1

使用compareTo方法,如何使用迭代器找出数组中的最大值?

简单地说:

Iterator<E> it = collection.iterator;
E max = null;
while(it.hasNext()) {
    if(max == null) {
        max = it.next();
    } else {
        e = it.next();
        if(e.compareTo(max) > 0) {
            max = e;
        }
    }
}
Iterator it=collection.Iterator;
E max=null;
while(it.hasNext()){
如果(max==null){
max=it.next();
}否则{
e=it.next();
如果(例如,与(最大值)>0相比){
max=e;
}
}
}
简单地说:

Iterator<E> it = collection.iterator;
E max = null;
while(it.hasNext()) {
    if(max == null) {
        max = it.next();
    } else {
        e = it.next();
        if(e.compareTo(max) > 0) {
            max = e;
        }
    }
}
Iterator it=collection.Iterator;
E max=null;
while(it.hasNext()){
如果(max==null){
max=it.next();
}否则{
e=it.next();
如果(例如,与(最大值)>0相比){
max=e;
}
}
}

如果只想查找数组中的最大元素(无需显式使用迭代器和compareTo),则可以将数组转换为集合或流:

Integer[] objectArray = {3,66,4,22,4};
List<Integer> objectList = Arrays.asList(objectArray);
System.out.println(Collections.max(objectList));

int[] primitiveArray = {3,66,4,22,4};
IntStream intStream = Arrays.stream(primitiveArray);
System.out.println(intStream.max().getAsInt());
Integer[]objectArray={3,66,4,22,4};
List objectList=Arrays.asList(objectArray);
System.out.println(Collections.max(objectList));
int[]基元数组={3,66,4,22,4};
IntStream IntStream=Arrays.stream(primitiveArray);
System.out.println(intStream.max().getAsInt());

Collections.max
在引擎盖下使用迭代器和比较器(正如您通过阅读其源代码所看到的),但第二种方法不使用(因为它使用原语)。

如果您只想在数组中查找最大元素(而不显式使用迭代器和比较器),然后可以将数组转换为集合或流:

Integer[] objectArray = {3,66,4,22,4};
List<Integer> objectList = Arrays.asList(objectArray);
System.out.println(Collections.max(objectList));

int[] primitiveArray = {3,66,4,22,4};
IntStream intStream = Arrays.stream(primitiveArray);
System.out.println(intStream.max().getAsInt());
Integer[]objectArray={3,66,4,22,4};
List objectList=Arrays.asList(objectArray);
System.out.println(Collections.max(objectList));
int[]基元数组={3,66,4,22,4};
IntStream IntStream=Arrays.stream(primitiveArray);
System.out.println(intStream.max().getAsInt());

Collections.max
在引擎盖下使用了迭代器和compareTo(通过阅读其源代码可以看到),但第二种方法没有(因为它使用的是原语)。

尝试一下,让我们知道你在哪里遇到了麻烦。我只是一个试图了解compareTo方法用法的老人,谢谢你的评论。我真希望我能回来做作业@Stevenhanse试试看,让我们知道你在哪里遇到了麻烦。我只是一个试图了解比较法用法的老人,谢谢你的评论。我真希望我能回来做作业@Stevenhansenthan谢谢你的回答,e呢?不是必须初始化吗?谢谢你的回答,e呢?它不是必须初始化吗?