javalistnetbeans

Can't access objects stored in an ArrayList


I created an arraylist.

List FWD = new ArrayList<Coords>();
FWD.add(new Coords(42.41, 37.23));
FWD.add(new Coords(37.09, 47.8));
FWD.add(new Coords(36.83, 48.42));

and then I want to access each element of the list in this way:

FWD.get(3).[some method from Coords class]

but Netbeans says:

cannot find symbol symbol: method getIndexX() location: class Object

Coords class:

public class Coords {
    private double weightY, indexX;

    Coords(double x, double y){
        setIndexX(x);
        setWeightY(y);
    }

    public double getWeightY() {
        return weightY;
    }

    public void setWeightY(double weightY) {
        this.weightY = weightY;
    }

    public double getIndexX() {
        return indexX;
    }

    public void setIndexX(double indexX) {
        this.indexX = indexX;
    }
}

Solution

  • Your variable FWD is of type List, but it actually contains an ArrayList<Coords>, which is a List<Coords>, but the compiler does not know this. If FWD is declared as a List<Coords> this code should work as is.

    You should also note that Java lists are 0-indexed, so the third element of the list has an index of 2, so in the example you have provided there will not be an element retrieved, although this will only appear at runtime.

    As a final point, it may be interesting to note that Java convention dictates variables to be named in camelCase with, so you may prefer to name your variable fwd or similar (Perhaps using a full words if not too excessive).