【问题标题】:JAVA: access a key which is an object in an iteratorJAVA:访问作为迭代器中的对象的键
【发布时间】:2015-05-18 10:16:20
【问题描述】:

我试图以粗体访问的输出。

键: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;
}

如何访问密钥中保存的数据?

谢谢。

【问题讨论】:

  • Iterator<Integer> entries = ... 等也许?
  • 首先...不要使用raw types。由于PropertyInteger 看起来像是您自己的类之一,您应该知道如何访问它的属性之一。

标签: java iterator


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    可能有帮助的是大量的泛型。

    条目中的键和值是什么类型?现在我将使用 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;
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多