不知何故,我的旧问题已关闭,所以我打开了一个新问题:
我正在使用 Java 泛型从 SQL 查询中实现泛型双向哈希映射。它应该能够来回映射字符串、整数对的任意组合。它应该像这样使用:
String sql = "SELECT string_val, int_val FROM map_table";
PickMap<String, Integer> pm1 = new PickMap<String, Integer>(sql);
String key1 = "seven";
Integer value1 = pm1.getLeft2Right(key1);
Integer key2 = 7;
String value2 = pm1.getRightToLeft(key2);
当然应该可以创建一个 pm (Integer, Integer) 等等...
我的 Pick Map 实现如下所示(没有 getter ......):
public class PickMap<L, R> {
private final HashMap<L, R> left2Right = new HashMap<L, R>();
private final HashMap<R, L> right2Left = new HashMap<R, L>();
public PickMap(String sql) throws OException {
DTable d = new DTable(sql);
int colTypeL = d.t.getColType(1);
int colTypeR = d.t.getColType(2);
Extractor<L> extLeft = (Extractor<L>) getInstance(colTypeL);
Extractor<R> extRight = (Extractor<R>) getInstance(colTypeR);
int numRows = d.t.getNumRows();
for(int i=1;i<=numRows;i++) {
L leftVal = extLeft.extract(d, i);
R rightVal = extRight.extract(d, i);
this.left2Right.put(leftVal, rightVal);
this.right2Left.put(rightVal, leftVal);
}
}
private Extractor<?> getInstance(int type) {
if(type == 1)
return new IntExtractor();
else
return new StringExtractor();
}
}
interface Extractor<E> {
E extract(DTable source, int row);
}
class IntExtractor implements Extractor<Integer> {
@Override
public Integer extract(DTable source, int row) {
int value = 5;
return new Integer(value);
}
}
class StringExtractor implements Extractor<String> {
@Override
public String extract(DTable source, int row) {
String retVal = "hello";
return retVal;
}
}
我没有编译器错误,我很确定它会以这种方式工作。但是我在“getInstance”方法上收到未经检查的强制转换警告,我将提取器(E)转换为提取器(L)......
我应该如何正确施放?或者我错过了什么?还是我应该压制这些警告?