gpt4 book ai didi

java - 如何改进使用 Java 泛型编写的实用算法的设计和可读性?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:19:41 25 4
gpt4 key购买 nike

我发现在使用 java 集合时,尤其是在使用泛型编写实用程序方法时,我的代码通常是丑陋和臃肿的,充满了空检查、嵌套循环和重复。专注于这个例子,我想要改进的想法。

假设我们有一个 EnumMap,其值是评级列表。例如,假设 enum 本身代表水果,每个值代表不同人给出的列表评级。

APPLE  -> [1,   3,   4] 
ORANGE -> [2, 0, 5]

John rated apple 1, Mary rated apple 3, Steve rated apple 4
John rated orange 2, Mary rated orange 0, Steve rated orange 5
Note the specific names are irrelevant and provided only to clarify the setup

现在我们要编写一个实用程序方法,它接受与上面类似的数据结构,并返回每个人最喜欢的水果列表。因此,上述示例数据的预期结果将是:[ORANGE, APPLE, ORANGE 因为 2 > 13 > 05 > 4

以下是我目前执行此操作的方法。我想要一种同样(或更)高效但更简洁的方法来编写相同的算法。

谢谢!

public class MyListUtil {

public static <K extends Enum<K>, T extends Object & Comparable<? super T>> List<K> maxKeysByIndex(EnumMap<K, List<T>> enumMap) {
Iterator<K> keysIter = enumMap.keySet().iterator();
int sizeOfAllLists = enumMap.get(keysIter.next()).size();
List<K> ret = new ArrayList<K>();

for (int i=0; i<sizeOfAllLists; i++) {
keysIter = enumMap.keySet().iterator();
K maxIndexKey = null;
T maxIndexVal = null;

while (keysIter.hasNext()){
K curKey = keysIter.next();
T curVal = enumMap.get(curKey).get(i);
if (maxIndexVal == null || curVal.compareTo(maxIndexVal) > 0) {
maxIndexVal = curVal;
maxIndexKey = curKey;
}
}
ret.add(maxIndexKey);
}

return ret;
}
}

最佳答案

这真的很丑。

IMO 在这里使用枚举是错误的。枚举应该是编程常量,而不是人们的喜好。

您应该创建一个类 PersonFruitPreference,它使用一个 Map 来允许 Person 设置对水果的偏好。还要添加一个方法 getFavoriteFruit()

关于java - 如何改进使用 Java 泛型编写的实用算法的设计和可读性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10523822/

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