gpt4 book ai didi

java - 返回最接近 val 的元素的通用编程

转载 作者:行者123 更新时间:2023-12-01 14:08:05 26 4
gpt4 key购买 nike

需要实现类似于 java.util.Collections 的类的方法 – a具有静态方法的库类旨在为一般元素集合提供有用的功能。如果它们是整数元素,我知道如何执行此操作。现在我需要将代码转换为通用类型。任何帮助将不胜感激!

来自:

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

最佳答案

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

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;
}

}

关于java - 返回最接近 val 的元素的通用编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18749367/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com