【问题标题】:Iterating over an AttributeSet Enumeration遍历 AttributeSet 枚举
【发布时间】:2011-09-01 19:45:35
【问题描述】:

我有以下代码:

    private static boolean hasTargetStyle(AttributeSet attributes) {
        final Enumeration<?> attributeNames = attributes.getAttributeNames();
        while (attributeNames.hasMoreElements()) {
            final Object attributeName = attributeNames.nextElement();
            if (attributeName.equals(MY_STYLE_NAME)) {
                return true;
            }
        }

        return false;
    }

现在我认为这段代码会逐步遍历每个属性名称。但它只给了我所有其他属性名称(带有偶数索引的属性名称)。

这里出了什么问题?

【问题讨论】:

  • 你的代码看起来不错;问题可能出在输入 AttributeSet

标签: java enumeration


【解决方案1】:

我在调试器中查看的内部列表具有交替的名称和值。所以,我的代码在某种意义上是正确的,但我的意图是错误的。

【讨论】:

    【解决方案2】:

    我怀疑这是java.util.Enumeration 的问题(尽管这只是一个接口,实际实现可能有错误)。您的实现对我来说看起来不错。

    其他想法:最初的AttributeSet 可能只包含所有其他属性。尝试设置断点并查看实际属性集的内部结构。

    【讨论】:

      【解决方案3】:

      目前我没有发现您的代码有任何问题,但请尝试使用 Collections.list

      private static boolean hasTargetStyle(AttributeSet attributes) {
          final List<?> attributeNames = Collections.list(attributes.getAttributeNames());
      
          for(Object name: attributeNames){
              if(name.equals(MY_STYLE_NAME)){
                  return true;
              }
          }
      
          return false;
      }
      

      【讨论】:

        【解决方案4】:

        我认为它没有索引 - Set 没有索引。而且代码看起来不错。除非 getAttributeNames() 返回错误实现的枚举,否则它应该可以工作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-12-12
          • 2015-08-13
          • 1970-01-01
          • 2016-06-08
          • 2015-08-19
          • 1970-01-01
          • 1970-01-01
          • 2010-10-03
          相关资源
          最近更新 更多