gpt4 book ai didi

java - Java 中 ArrayList 不兼容的类型

转载 作者:行者123 更新时间:2023-12-02 09:31:17 25 4
gpt4 key购买 nike

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

旅行类别

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

我正在尝试将 GPS ping 添加到此行程列表,但前提是 p 的时间在此行程列表中的最后一次之后。我对 Java 很陌生,正在努力解决语法问题,如果有帮助,我将不胜感激。

最佳答案

List 中的第一个元素的索引为 0,要获取最后一个元素:

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

但我认为,最好存储 maxPingTime 以便在添加新 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.关注Encapsulation OOP 原则:GPSping 应该是最终的,pingList 不应该直接检索。

关于java - Java 中 ArrayList 不兼容的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57952189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com