简体   繁体   English

Java中的ArrayList不兼容类型

[英]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. 我试图将GPS ping添加到此行程列表,但前提是p的时间晚于该行程列表的最后一次。 I am very new to Java and am struggling with wrapping my head around the syntax some help would be greatly appreciated. 我对Java还是很陌生,并且正在竭尽全力围绕语法进行一些帮助,将不胜感激。

First element in List has index 0 , to to get the last one: List第一个元素的索引为0 ,以获得最后一个:

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

But I think, it's better to store maxPingTime to check it before add new GPSping : 但我认为,最好在添加新的GPSping之前存储maxPingTime进行检查:

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

PS Pay attention on Encapsulation OOP principle: GPSping should be final and pingList should not be directly retrieved. PS请注意封装 OOP原理: GPSping应该是最终的,而pingList不应该直接检索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM