L0n35
L0n35

Reputation: 105

ArrayList incompatible types in Java

public class GPSping {
    private double pingLat;
    private double pingLon;
    private int pingTime;
}

The Trip class

public class Trip {
    private ArrayList<GPSping> pingList;

    public Trip() {
        pingList = new ArrayList<>();
    }

    public Trip(ArrayList<GPSping> triplist) {
        pingList = new ArrayList<>();
    }

    public ArrayList<GPSping> getPingList() {
        return this.pingList;
    }

    public boolean addPing(GPSping p) {
        int length = pingList.size();
        int Time = pingList.get(length);
        if (p.getTime() > this.pingList[length]) {
            pinglist.add(p);
            return True;
        } else {
            return False;
        }
    }
}

I am trying to add a GPS ping to this trip list but only if the time of p is after the last time in this trip list. I am very new to Java and am struggling with wrapping my head around the syntax some help would be greatly appreciated.

Upvotes: 0

Views: 95

Answers (1)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

First element in List has index 0, to to get the last one:

int Time = pingList.get(length - 1);

But I think, it's better to store maxPingTime to check it before add new GPSping:

class Trip {

    private final List<GPSping> pingList = new ArrayList<>();
    private int maxPingTime = Integer.MIN_VALUE;

    public List<GPSping> getPingList() {
        return pingList.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(pingList);
    }

    public boolean addPing(GPSping p) {
        if (p.getPingTime() <= maxPingTime)
            return false;

        pingList.add(p);
        maxPingTime = p.getPingTime();
        return true;
    }
}

final class GPSping {

    private final double pingLat;
    private final double pingLon;
    private final int pingTime;

    public GPSping(double pingLat, double pingLon, int pingTime) {
        this.pingLat = pingLat;
        this.pingLon = pingLon;
        this.pingTime = pingTime;
    }
}

P.S. Pay attention on Encapsulation OOP principle: GPSping should be final and pingList should not be directly retrieved.

Upvotes: 1

Related Questions