如果单词/数字的添加顺序发生变化,我的最小方法会给出不同的结果



所以基本上我的代码正在做问题所说的。按照现在代码的布局方式,它给出了正确的结果,但是当我更改 .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);
}
}

你的比较测试是错误的。目前,您正在选择最大值。

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

应该是

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

另外,smallestPos++;应该smallestPos=i;

当前,您正在返回"最小"值更改的次数计数。

使用 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
}

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

最新更新