如果添加 words/numbers 的时间顺序发生变化,我的“最小方法”会给出不同的结果

my 'smallest method gives different results if order of when the words/numbers are added is changed

所以基本上我的代码就是按照问题所说的去做。现在代码的布局方式给出了正确的结果,但是当我更改 .add 代码段的顺序时,它每次都会给出不同的结果。我觉得 compareTo 方法很好,但是我错过了什么吗?我正在尝试获得最小的结果。

提前致谢。

package lists;

import java.util.*;

public class Lab4 {
    public static <T extends Comparable> int smallest(List<T> l) {
        if (l.size() == 0) 
            return -1;
        else {
            Iterator<T> it = l.iterator();
            T smallestSoFar = it.next();
            T temp;

            int smallestPos = 0;
            int i = 0; //used to indicate position in list of next item
            while (it.hasNext()) {
                temp = it.next();

                if (temp.compareTo(smallestSoFar) > 0) {
                    smallestSoFar = temp;
                    smallestPos++;
                }
                i++;
            }

            return smallestPos;
        }
    }

    public static <T extends Comparable> void deleteSmallest(List<T> l) { // for exercise 3
    }

    public static void main(String[] args) {
        Vector<String> vec1 = new Vector<String>();
        vec1.add("Hello");
        vec1.add("xxxx");
        vec1.add("world");
        vec1.add("aardvark");

        int smallPos = smallest(vec1);
        if (smallPos != -1)
            System.out.println("smallest entry is " + vec1.elementAt(smallPos) + " at position " + smallPos);
        Vector<Integer> vec2 = new Vector<Integer>();

        vec2.add(new Integer(47));
        vec2.add(new Integer(247));
        vec2.add(new Integer(17));
        vec2.add(new Integer(399));

        smallPos = smallest(vec2);
        if (smallPos != -1)
            System.out.println("smallest entry is " + vec2.elementAt(smallPos) + " at position " + smallPos);
    }
}

使用 java8 可以使 smallest() 方法更紧凑:

public static <T extends Comparable<T>> int smallest( List<T> list ){
    return list.stream()               // get Stream<T> from list
        .sorted(Comparable::compareTo) // Stream<T> is now sorted
        .mapToInt(list::indexOf)       // maps Stream<T> to an IntStream consisting of indices
        .findFirst()                   // find the first value (the smallest)
        .orElse(-1);                   // if nothing found, hence list was empty, then return -1
}

当我用我的函数测试它时,没有发现不一致的地方

你的对比测试方法是错误的。当前您正在选择最大值。

if (temp.compareTo(smallestSoFar) > 0) {

应该是

if (temp.compareTo(smallestSoFar) < 0) {

此外,smallestPos++;应该是smallestPos=i;

目前您正在返回 "smallest" 值更改次数的计数。