0

コレクション内の選択した値より大きいすべての値を検索するメソッドを作成しましたが、正しくない場合があります。誰でも理由がわかりますか?これらは失敗の 2 つの例です:

 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>

テレメータ - 距離用

 * 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);



}

値を大きくする方法

 /**
    * 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

あなたのコードは非常に不完全であり、「距離」の概念は誤解を招くものです (距離は一般的に非負であると想定されています)。ただし、間違った結果を引き起こす可能性があることの 1 つは、a.next() を 2 回呼び出していることです。これにより、同じ "while" 反復でイテレータが 2 回 (条件が true の場合) 進められます。

于 2013-09-16T20:48:10.080 に答える