我正在开展一个项目,我必须从数据库中读取一系列功能(属性)(以CSV文件的形式)。
这是文件的外观(格式化一点以便于阅读):
IsFast; Speed; IsRed; R; G; B
T; 123.4; F; 0.0; 0.0; 1.0
F; 21.3; T; 1.0; 0.0; 0.0
...
如您所见,T / F表示布尔值,而数字是浮点值。稍后可以添加或删除属性。
在我的代码中,我需要为每个实例(行)读取这些值,然后将它们传递给其他代码,然后再进一步处理数据。
我目前处理此问题的方法是使用以下类:
public abstract class Feature<T> {
public final String name;
public final T value;
public Feature(String name, T value) {
this.name = name;
this.value = value;
}
public abstract boolean test(T value);
}
public class BoolFeature extends Feature<Boolean> {
public BoolFeature(String name, boolean value) {
super(name, value);
}
@Override
public boolean test(Boolean value) {
return this.value;
}
}
public class DoubleFeature extends Feature<Double> {
public DoubleFeature(String name, double value) {
super(name, value);
}
@Override
public boolean test(Double value) {
return this.value < value;
}
}
然后,我正在解析CSV文件并创建BoolFeature
个对象以输入其他人的T / F和DoubleFeature
,并将其全部保存在List<Feature>
或{{1}中然后传递该集合。
然而,这导致了很多
功能是原始类型。对泛型类型功能的引用应该参数化
和
类型安全:方法测试(Object)属于原始类型功能。对泛型类型功能的引用应该参数化
代码如下:
Feature[]
有没有更简洁的方法来处理这样的问题?
将public abstract class Metric {
protected List<Feature> features; // this line gives warning #1 from above
public Metric(List<Feature> features) {
this.features = features;
}
public double getSplitQuality(Split split) {
return getImpurity(split.yes) + getImpurity(split.no);
}
public abstract double getImpurity(List<Instance> instances);
}
public class Split {
public final List<Instance> yes;
public final List<Instance> no;
public Split(List<Instance> instances, Feature feature) {
yes = new ArrayList<>();
no = new ArrayList<>();
for (Instance inst : instances)
if (inst.features.get(feature.name).test(feature.value)) // this line gives warning #2 from above
yes.add(inst);
else
no.add(inst);
}
}
public class Instance {
public HashMap<String, Feature> features = new HashMap<>();
public String output = null;
public Instance(String[] featureNames, String[] csvRow) {
/* parse CSV row, creating BoolFeatures and DoubleFeatures
and adding them to the HashMap, for example: */
if (csvRow[0].equals("T") || csvRow[0].equals("F"))
features.put(featureNames[0], new BoolFeature(featureNames[0], csvRow[0].equals("T")));
}
}
添加到<?>
的所有引用后,根据答案,之前发出警告#2的行现在会产生编译时错误:
类型Feature中的方法测试(捕获#2-of?)不适用于参数(捕获#3-of?)
答案 0 :(得分:1)
您的List<Feature>
使用原始类型Feature
(如警告所示)。如果您知道子类型Feature
有哪些,则可以使用泛型类型,例如List<Feature<Boolean>>
。
但是,如果您希望List<Feature
包含BoolFeature
和DoubleFeature
,则可以使用通配符类型List<Feature<?>>
答案 1 :(得分:0)
您的功能是否已编译?我怀疑,因为你没有宣布T.这个怎么样?
public abstract class Feature<T> {
public final String name;
public final T value;
public Feature(String name, T value) {
this.name = name;
this.value = value;
}
public abstract boolean test(T value);
}
我的日食中没有任何警告任何3个班级。