【问题标题】:Can only iterate over an array or an instance只能遍历数组或实例
【发布时间】:2017-01-20 08:18:40
【问题描述】:

在过去的一个小时里我一直在努力让它工作,我收到了错误

只能遍历数组或 java.lang.Iterable 的实例

public boolean register(Object parent, Class<?>... events) {
    boolean added = false;
    try {
        for (Link<?> link : parentLinkCache.get((List) Objects.requireNonNull(parent, "Object to be registered cannot be null"))) {
            if (events.length > 0) {
                for (Class<?> clazz : events) {
                    if (link.getEventClass() == clazz) {
                        this.backingMap.computeIfAbsent(link.getEventClass(), l -> new ConcurrentSkipListSet<>()).add(link);
                        added = true;
                        break;
                    }
                }
            } else {
                this.backingMap.computeIfAbsent(link.getEventClass(), l -> new ConcurrentSkipListSet<>()).add(link);
                added = true;
            }
        }
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    return added;
}

错误出现在parentLinkCache.get

【问题讨论】:

  • parentLinkCache.get(...) 返回什么类型的对象?它不是实现Iterable&lt;Link&lt;?&gt;&gt;的数组或类型。
  • 私有静态最终LoadingCache parentLinkCache = CacheBuilder.newBuilder()
  • parentLinkCache.get 会返回一个Object;那不是Iterable

标签: java arrays


【解决方案1】:

使用增强的 for 语句。

for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) Statement

Expression 的类型必须是 Iterable 或数组类型,否则会发生编译时错误。检查 parentLinkCache.get(...) 的返回类型。

可以看JLSThe enhanced for statement

【讨论】:

    【解决方案2】:

    您的缓存应该列出每个父母的链接。所以,

    替换

    LoadingCache<Object, Object> parentLinkCache = CacheBuilder.newBuilder();
    

    LoadingCache<Object, List<Link<?>>> parentLinkCache = CacheBuilder.newBuilder().build();
    

    由于 List 也是一个 Iterable,您可以在 enhanced for loop 中使用它。


    还有,

    CacheBuilder.newBuilder()
    

    返回CacheBuilder。如果你想要Cache,你应该写

    CacheBuilder.newBuilder().build()
    

    希望这会有所帮助。

    【讨论】:

    • 您好,感谢您的回复。当我这样做时,我得到 The method get(Objects.requireNonNull(parent, "Object to be unregistered cannot be null")) is undefined for type CacheBuilder
    • 如果替换指定类型,parentLinkCache 将不是CacheBuilder&lt;Object,Object&gt; 类型,而是LoadingCache&lt;Object, List&lt;Link&lt;?&gt;&gt;&gt; 类型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多