迭代LinkedHashMap显示编译错误

时间:2013-06-13 21:38:39

标签: java generics loops map

以下是AttributeValue类的代码 -

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown=true)
public class AttributeValue<T> {
    private T value;                    // value
    private Date timestamp;             // timestamp
    String valueType = null;        // class type of the value object

    @Deprecated
    private int classNumber = 0;        // internal

    private static Logger s_logger = Logger.getInstance(BEAttributeValue.class);

    @JsonProperty("v")
    public T getValue() {
        if (valueType != null && !value.getClass().getName().equalsIgnoreCase(valueType)) {
            value = convert(value, valueType);
        }
        return value;
    }

    @JsonProperty("v")
    public void setValue(T value) {
        this.value = value;
    }

    private T convert(Object other, String classType) {
        T value = null;
        if (other != null) {
            IJsonMapper mapper = JsonMapperFactory.getInstance().getJsonMapper();
            try {
                String json = mapper.toJson(other);
                Class<T> className = (Class<T>)Class.forName(classType);
                value = mapper.toPojo(json, className);
            } catch (Exception e) {
                s_logger.log(LogLevel.ERROR, "BEAttributeValue::convert(), caught an exception: \n",e.getStackTrace());
            }       
        }
        return value;
    }
}

问题陈述: -

现在我尝试使用以下代码迭代AttributeValue列表 -

for(AttributeValue<?> al: list) {

System.out.println(al.getValue());

}

当我在al上进行检查时,我认为价值为LinkedHashMap<K,V>,当我打印al.getValue()时,它会给我这个 -

{predictedCatRev=0;101;1,1;201;2, predictedOvrallRev=77;2,0;1,16;3, sitePrftblty=77;2,0;1671679, topByrGms=12345.67, usrCurncy=1, vbsTopByrGmb=167167.67}

所以我认为al.getValue将是Map,我可以像这样迭代它 -

for (Map.Entry<Integer, Integer> entry : al.getValue().entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

但它在entrySet()用红色给我编译错误。而且我不确定如何在检查时清楚地迭代value,我可以将其视为LinkedHashMap<K,V>

任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:1)

您需要执行强制转换。编译器不知道al.getValue()属于Map<Integer, Integer>类型,因此您必须具体告诉他:

for (Map.Entry<Integer, Integer> entry : ((Map<Integer, Integer>) al.getValue()).entrySet()) {