-1

我创建了一种方法来查找最接近集合中选定值的值。我不知道它是否会起作用,因为我不知道如何在 Junit 中为它编写测试用例。这种方法是否有效或对测试用例有任何想法。最近是由距离决定的。由于限制,我不能对这种方法使用数组列表。

遥测仪

  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 the element of c nearest to val.
    * The Collection c is not changed as a result of calling this method.
    *
    * @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 element e in c such that its distance from
    * val is minimum for all elements in c
    *
    */
   public static <T> T nearest(Collection<T> c, T val, Telemeter<T> tm) {
      if (c == null || c.size() == 0 || tm == null) {
         throw new IllegalArgumentException();
      }
      T answer = null;
      Iterator<T> itr = c.iterator();
      T one = itr.next();       
      while(itr.hasNext()) {

         T two = itr.next();
         if(Math.abs((tm.distance(one, val))) > Math.abs(tm.distance(two, val))) {
         answer = two; 
         }
      }    
      return answer;
   }
4

2 回答 2

0

你很接近..但你必须更新“一个”,否则你将总是将距离与集合的第一个元素进行比较。试试这个:

Iterator<T> itr = c.iterator();
T answer = itr.next();       
while(itr.hasNext()) {

    T two = itr.next();
    if(Math.abs((tm.distance(answer, val))) > Math.abs(tm.distance(two, val))) {
    answer = two; 
    }
}    
return answer;

我同意 ATG 的观点,您绝对应该为您编写的代码编写一些测试用例。尝试测试简单的场景以及更复杂的场景,例如数组中有重复项、值小于数组中的任何元素(您的代码应返回最低元素)等等。

于 2013-09-16T16:21:20.457 回答
0

您的问题在于您的代码null在具有单个元素的集合中返回,而它可能应该返回单个元素。

不过,老实说,您确实应该编写某种测试。如果您对 JUnit、TestNG 等感到不满意,并且绝对没有时间学习,那么您可以编写一个简单的 main 方法并使用值直到您满意为止。向 SO 社区寻求帮助可能会在短期内发现错误,但是当您重构此代码时,您将无法证明它继续按预期工作。

于 2013-09-16T16:30:45.137 回答