0

I have created a method that finds all values greater than a selected value in a Collection but sometimes it is incorrect. Can anyone see why? These are two instances of failure:

 Selector test case - method greater: val less than all elements. 
 java.lang.AssertionError: c = [-5,-2,0,4,8,15,50] val = -99 expected:<true> 
 but was:<false>

 Selector test case - method greater: val equal to elements. 
 java.lang.AssertionError: c = [-5,-2,0,4,8,15,50] val = -5 expected:<true> 
 but was:<false>

Telemeter - for distance

 * Defines abstract behavior of distance finding between objects.
 * As a subinterface of Comparator, Telemeter also defines a
 * total order on objects of the type parameter E.
 * 
 *
 *
 * @param <E> the type on which distance and order are defined
 *
 */
public interface Telemeter<E> extends Comparator<E> {

   /**
    * Returns the distance between e1 and e2.
    *
    * @param e1 the first object
    * @param e2 the second object
    * @return the distance between e1 and e2
    *
    */

   public double distance(E e1, E e2);



}

Method for greater values

 /**
    * Return a Collection of all the elements of c that are greater than val.
    * If c contains no elements greater than val, this method returns an
    * empty Collection.
    *
    * @param <T> the type variable for this method
    * @param c the Collection to be searched
    * @param val the reference value
    * @param tm the Telemeter that measures distance
    * @return the a Collection of the elements e in c 
    * such that e is greater than val
    *
    */
   public static <T> Collection<T> greater(Collection<T> c, T val, 
      Telemeter<T> tm) {
      if (c == null || c.size() == 0 || tm == null) {
         throw new IllegalArgumentException();
      }

      Collection<T> answer = new ArrayList<T>();
      Iterator<T> a = c.iterator();
      while  (a.hasNext()) {
         if (tm.distance(a.next(), val) < 0) {
            answer.add(a.next());
         }
      }   
      return answer;   




}
4

2 回答 2

0

您的代码非常不完整,并且“距离”的概念具有误导性(距离通常应该是非负的)。但是可能导致错误结果的一件事是您调用了 a.next() 两次,这将在同一个“while”迭代中将迭代器推进两次(如果条件为真)。

于 2013-09-16T20:48:10.080 回答
0

您的错误是您在循环内调用a.next() 了两次-因此您将下一个元素添加到您比较的元素中:调用next()不仅返回下一个元素,它还推进了迭代器。

但!你的设计全错了。方法的泛型类型不应Comparable扩展Comparator。那么你就不需要你的 interface 了Telemetet

那么你的方法就是:

public static <T extends Comparable<T>> Collection<T> greater(Collection<T> c, T val) {
    if (c == null || c.size() == 0 || val == null) {
       throw new IllegalArgumentException();
    }

    Collection<T> answer = new ArrayList<T>();
    for (T a : c) {
       if (val.compareTo(a) < 0) {
           answer.add(a);
       }
    }   
    return answer;
}
于 2013-09-16T22:05:31.873 回答