【问题标题】:(java) incompatible types?(java) 不兼容的类型?
【发布时间】:2018-01-06 14:43:54
【问题描述】:

我在编译时遇到错误:

'不兼容的类型 - 找到单位但预期单位'

这是为什么? 这是从方法返回时,我什至可以将返回的数据解析为“单元”并且它工作正常,为什么会出现这个错误? 我在我创建的集合中使用迭代器这一事实与它有什么关系吗?我没有留下迭代器类型 E,因为我特别希望这个集合用于一种类型的对象。

private class unitHashIterator<unit> implements Iterator<unit> {
  private unitHash hash;
  private int nextIndex;
  private unitHashIterator(unitHash u) {
    hash = u; nextIndex = 0;
  }
  public unit next() {
    if(!hasNext())
      throw new NoSuchElementException();
    return hash.data[nextIndex++]; << HERE OCCURS THE ERROR
  }
}

这个类包含在一个集合中。

'不兼容的类型 - 找到单位但预期单位'

【问题讨论】:

  • 如果没有看到实际的错误消息(或 消息)和突出显示错误所在行的实际源代码,将无法回答。
  • 私有类 unitHashIterator 实现 Iterator { private unitHash hash;私有int nextIndex;私有 unitHashIterator(unitHash u) { hash = u;下一个索引 = 0; } ... public unit next() { if(!hasNext()) throw new NoSuchElementException();返回 hash.data[nextIndex++];
  • hash.data[nextIndex++] 究竟返回什么? hash.data 是什么?
  • 顺便说一句,类名应该以大写字母开头

标签: java


【解决方案1】:

不管 unitHash 的定义如何,都不能保证它包含 unit 类型的元素,因为 unitHash 不是对类型进行参数化的,但 unitHashIterator 是。我怀疑你要么打算写class unitHashIterator 而不是class unitHashIterator&lt;unit&gt;,要么是private unitHash&lt;unit&gt; hash; 而不是private unitHash&lt;unit&gt; hash;

您收到的错误消息可能是因为编译器希望返回与类型变量unit 相同类型的东西,但hash 返回的东西恰好也有一些具体类型(不是类型变量)命名为unit

【讨论】:

  • 类头的变化修复了它。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-29
  • 1970-01-01
  • 2015-09-25
  • 2016-04-12
  • 1970-01-01
相关资源
最近更新 更多