0

需要实现类似于 java.util.Collections 的类的方法——一个具有静态方法的库类,旨在为元素的一般集合提供有用的功能。如果它们是整数元素,我知道该怎么做。现在我需要将代码转换为通用类型。任何帮助都感激不尽!

从:

import java.util.Arrays;

public final class Selector {

  private Selector() {
  } 

  public static int nearest(int[] a, int val) {
      if (a == null || a.length == 0) {
         throw new IllegalArgumentException("a is null or has zero-length");
      }
      int idx = 0;
      int distance = Math.abs(a[0]-val);
      for (int c = 1; c < a.length; c++) {
         int cdistance = Math.abs(a[c] - val);
         if (cdistance <= distance) {
            idx = c;
            distance = cdistance;
         }
      }
      int theNumber = a[idx];
      return theNumber;
   }

}

import java.util.Collections;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;

public final class Selector {
  private Selector() { }

  public static <T> T nearest(Collection<T> c, T val, Telemeter<T> tm) {
   .
   .
   .
  }
}

遥测仪

import java.util.Comparator;

public interface Telemeter<E> extends Comparator<E> {
  double distance(E e1, E e2);
}
4

1 回答 1

1

使用您现有的代码,如果您可能想将其转换为通用代码,代码将类似于以下内容:

import java.util.Arrays;

public final class Selector {

  private Selector() {
  } 

  public static <T> T nearest(Collection<T> c, T val, Telemeter<T> tm) {
      if (c == null || c.isEmpty()) {
         throw new IllegalArgumentException("a is null or has zero-length");
      }
      int idx = 0;
      double distance = tm.distance(c.get(0), val);
      for (int i = 1; i < c.size(); i++) {
         double cdistance = tm.distance(c.get(i), val);
         if (cdistance <= distance) {
            idx = i;
            distance = cdistance;
         }
      }
      int theNumber = c.get(idx);
      return theNumber;
   }

}
于 2013-09-11T19:47:03.570 回答