gpt4 book ai didi

Java:在此设计中使用泛型的替代方案是什么?

转载 作者:行者123 更新时间:2023-12-02 03:51:48 24 4
gpt4 key购买 nike

我正在开发一个开源 Java 库,它允许人们计算具有有限数量值的属性的某些数量,例如基尼指数。 (正式地,它计算与属性 A 相关的离散分布的基尼指数,但这与这里无关。)

例如,人们将能够执行以下操作

String[] namesArray = {"primary_school", "high_school", "university"};
Calculator<String> calc =new Calculator<String>(namesArray);

// p.getEducationLevel() returns `"primary_school"`, `"high_school"`, or `"university"`.
for (Person p : peopleCollection) {
calc.increment(p.getEducationLevel());
}

// e.g. the Gini index of the distribution
double currentStat = calc.getCurrentValue();

这个想法是允许库的用户使用自己的类型来引用属性值;在本例中,我使用字符串(例如 "primary_school" )。但我可能想使用整数甚至我自己的类型 AttributeValue .

我通过定义来解决这个问题

public class Calculator<T> {
/* ... */
}

但是,使用泛型会在实现中导致一些问题:例如,如果我想维护 (T, double) 类型对的集合。 ,我必须进行令人讨厌的类型转换:

public class Calculator<T>
/* ... */
private Queue<StreamElement<T>> slidingWindow;
/* ... */
class StreamElement<T> {
private T label;
private double value;

StreamElement(T label, double value) {
this.label = label;
this.value = value;
}

public T getLabel() {
return label;
}
public double getValue() {
return value;
}
}
/* ... */
slidingWindow.add(new StreamElement<T>(label, value));
if (slidingWindow.size() > windowSize) {
StreamElement lastElement = slidingWindow.remove();
// XXX: Nasty type cast
decrement((T)lastElement.getLabel(), lastElement.getValue());
}
/* ... */
}

这是 javac 生成的警告:

Calculator.java:163: warning: [unchecked] unchecked cast
decrement((T)lastElement.getLabel(), lastElement.getValue());
^
required: T
found: Object
where T is a type-variable:
T extends Object declared in class Calculator
1 warning

更新。如果我不进行类型转换,我会得到

Calculator.java:163: error: no suitable method found for decrement(Object,double)
decrement(lastElement.getLabel(), lastElement.getValue());
^
method Calculator.decrement(T) is not applicable
(actual and formal argument lists differ in length)
method Calculator.decrement(T,double) is not applicable
(actual argument Object cannot be converted to T by method invocation conversion)
where T is a type-variable:
T extends Object declared in class Calculator
1 error

问题:

  • 什么是正确、干净的类型转换方法?
  • 这里使用泛型的替代方法是什么?
  • 更具体地说,定义一个类 Label 会更好吗?哪个用户可以扩展到 MyLabel然后使用 MyLabel属性值? 这意味着 Calculator将不再是泛型类型;在实现中我们有 class StreamElement { Label label; /* ... */ }等等。

最佳答案

我认为你只是犯了一些错误。

这是正确的实现:

        /* ... */
slidingWindow.add(new StreamElement<T>(label, value));
if (slidingWindow.size() > windowSize) {
// Don't forget the generic argument at StreamElement
StreamElement<T> lastElement = slidingWindow.remove();
decrement(lastElement.getLabel(), lastElement.getValue());
}
/* ... */

关于Java:在此设计中使用泛型的替代方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35816362/

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