Search code examples
javalistloopsibeacon-androidestimote

For loop iterator type not the same as type I am trying to access


I am trying to iterate through a for loop and set elements of an list based on the iteration it is at, but the iteration type is not the same type as the list I want to access

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

The error displayed is that beacon is not the correct type, it is supposed to be an integer, but Beacons are not integers. Does anyone know a way to add another iterator or set beacon to an integer temporarily?

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

Btw Beacons are just some object I made, but they consists of UUID, major, and minor numbers. This might be irrelevant, but just incase you wanted to know. Thank you!


Solution

  • You need to use a Map instead of a 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;
    }
    

    When you do this you must also implement equals() and hashCode() in Beacon based on whatever "equality" means, and they must be consistent with each other. Read the Javadoc for the Map interface.

    In your case it is likely that "equals" has to consider the UUID and major/minor version numbers. The following assumes major/minor are primitive types, and that UUID cannot be null. Add extra checking or substitute equals() for == as appropriate:

    @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();
    }