簡體   English   中英

迭代LinkedHashMap顯示編譯錯誤

[英]Iterating the LinkedHashMap shows compilation error

以下是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>

誰能幫我這個?

你需要做一個演員 編譯器不知道al.getValue()的類型為Map<Integer, Integer> ,因此您必須專門告訴他:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM