JAVA:访问一个键,它是迭代器中的一个对象

时间:2015-05-18 10:16:21

标签: java iterator

我尝试以粗体显示的输出。

  

Key:PropertyInteger {name = age,clazz = class java.lang.Integer, values = [0,1,2,3,4,5,6,7] },值: 4

我需要访问PropertyInteger值

给我上述输出的代码是

private List blockInfo() {
    ArrayList arraylist = Lists.newArrayList();
    arraylist.add("");

    BlockPos pos = this.mc.objectMouseOver.getBlockPos();
    IBlockState state = this.mc.theWorld.getBlockState(pos);           

    Iterator entries = state.getProperties().entrySet().iterator();

    while(entries.hasNext()) {
        Entry entry = (Entry) entries.next();
        Object key = entry.getKey();
        Object value = entry.getValue();            

        System.out.println("Key: " + key + ", Value: " + value);

    }     

    return arraylist;
}

如何访问密钥中的数据?

感谢。

2 个答案:

答案 0 :(得分:0)

可能有帮助的是泛型的很好分享。

条目中的键和值有哪些类型?到现在为止,我将使用KeyType和ValueType存根。

类BlockPos和IBlockState是您自己的库吗?请提供链接或代码片段。

private List<String> blockInfo() {

//if you're going to add Strings, parametrize it
List<String> arraylist = Lists.newArrayList();
arraylist.add("");

BlockPos pos = this.mc.objectMouseOver.getBlockPos();
IBlockState state = this.mc.theWorld.getBlockState(pos);           

//to achieve this, the state.getProperties().entrySet() should be parametrized too
//Entry<KeyType, ValueType> presupposes that there's a Map<KeyType, ValueType> 
//somewhere in state.getProperties()
Iterator<Entry<KeyType, ValueType>> entries = state.getProperties().entrySet().iterator();

while(entries.hasNext()) {
    //no cast needed now
    Entry<KeyType, ValueType> entry =  entries.next();
    KeyType key = entry.getKey();
    ValueType value = entry.getValue();            

    //Here you have the exact types and can retrieve any information.

}     

return arraylist;

}

答案 1 :(得分:0)

你应该使用HashMap而不是List,比List快,并通过键返回值。