【问题标题】:For loop iterator type not the same as type I am trying to access对于循环迭代器类型与我尝试访问的类型不同
【发布时间】:2016-06-30 15:26:02
【问题描述】:

我正在尝试遍历 for 循环并根据其所在的迭代设置列表的元素,但迭代类型与我要访问的列表类型不同

private List<Double> myBeaconDistances = new ArrayList<>();

private List getBeaconDistances(List<Beacon> beacons){
    for (Beacon beacon : beacons) {
        double distance = Utils.computeAccuracy(beacon);
        this.myBeaconDistances.set(beacon, distance);

    }

    return myBeaconDistances;
}

显示的错误是信标类型不正确,它应该是整数,但信标不是整数。有谁知道添加另一个迭代器或临时将信标设置为整数的方法?

distance = Utils.commputeAccuracy(beacon) will return an double.

顺便说一句,信标只是我制作的一些对象,但它们由 UUID、主要和次要数字组成。这可能无关紧要,但以防万一您想知道。谢谢!

【问题讨论】:

  • 您是否尝试存储由信标和距离组成的键值对,以便给定信标您可以查找距离?如果是这样,您需要Map&lt;Beacon,Integer&gt;,而不是List。此外,如果是这种情况,Beacon 必须正确实现 equals()hashCode()
  • 有点吹毛求疵:尝试理解编译器给你的错误信息真的很有帮助!吉姆加里森是对的,顺便说一句。
  • @JimGarrison 是的,这就是我想要做的,谢谢你我会实现的

标签: java list loops ibeacon-android estimote


【解决方案1】:

您需要使用Map 而不是List

private Map<Beacon,Double> myBeaconDistances = new HashMap<>();

private Map<Beacon,Double> getBeaconDistances(List<Beacon> beacons){
    for (Beacon beacon : beacons) {
        double distance = Utils.computeAccuracy(beacon);
        this.myBeaconDistances.put(beacon, distance);

    }

    return myBeaconDistances;
}

执行此操作时,您还必须根据“平等”的含义在Beacon 中实现equals()hashCode(),并且它们必须彼此一致。阅读 Map 接口的 Javadoc。

在您的情况下,“equals”可能必须考虑 UUID 和主要/次要版本号。以下假设主要/次要是原始类型,并且 UUID 不能为空。酌情添加额外检查或将equals() 替换为==

@Override
public boolean equals(Object other)
{
    if (this == other) return true;
    if (other == null || !this.isAssignableFrom(other)) return false;
    Beacon b = (Beacon) other;
    return this.uuid.equals(b.uuid) && this.major == b.major && this.minor == b.minor;
}

@Override
public int hashCode()
{ 
    return 2047*this.major + this.minor + this.uuid.hashCode();
}

【讨论】:

    【解决方案2】:

    你在一个 ArrayList 上调用 set。第一个参数应该是 int,而不是 Beacon 类型。

    this.myBeaconDistances.set(beacon, distance);

    https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#set(int,%20E)

    【讨论】:

      猜你喜欢
      • 2017-11-02
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 2011-07-09
      • 2023-03-29
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多