2017-07-29 28 views
0

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

回答

3

你对比测试是围绕走错了路。目前您正在选择最大的价值。

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

应该

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

此外,smallestPos++;smallestPos=i;

目前您传回 “最小” 值改变的次数的计数。

2

随着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 
} 

,当我与我的功能测试,它没有矛盾

相关问题