【问题标题】:Iterating the LinkedHashMap shows compilation error迭代 LinkedHashMap 显示编译错误
【发布时间】:2013-06-13 21:38:39
【问题描述】:

下面是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&lt;K,V&gt;,当我打印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&lt;K,V&gt;

谁能帮我解决这个问题?

【问题讨论】:

  • 您在哪里/如何获得list?你能出示它的声明吗?

标签: java generics loops map


【解决方案1】:

您需要进行演员表。编译器不知道al.getValue()Map&lt;Integer, Integer&gt;类型,所以你要具体告诉他:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 2017-10-04
    • 2013-08-03
    • 1970-01-01
    相关资源
    最近更新 更多