gpt4 book ai didi

java - 异构数组列表

转载 作者:行者123 更新时间:2023-11-29 19:45:55 25 4
gpt4 key购买 nike

我是一个“Java noob”,所以请耐心等待我:)

我需要创建一个包含异构字段的特定结构。

我正在从 GPS 设备(我的智能手机)获取 Android.Location,我想存储所有位置,但我需要向每个位置添加一些其他字段。所以,我的结构将是这样的:

[0]: Location - String - int - String - int - String - String
[1]: Location - String - int - String - int - String - String
[2]: Location - String - int - String - int - String - String
[3]: Location - String - int - String - int - String - String
[4]: Location - String - int - String - int - String - String
...
[n]: Location - String - int - String - int - String - String

我不知道“行”的数量,因为它取决于一些变量(如时间、路线等)。

哪种方法最好用 Java 实现?

更新

这个解决方案是否正确?

public Class LocationPlus {
private Location location;
private String string1;
private int int1;
private String string2;
private int int2;

// Constructor, setters, getters
}

然后,在我的主要部分:

List<LocationPlus> locationPlus = new ArrayList<LocationPlus>();
locationPlus.add(new LocationPlus(location, “marco”, 1, “bianco”, 2));
locationPlus.add(new LocationPlus(location, “luca”, 3, “arancio”, 4));
locationPlus.add(new LocationPlus(location, “giovanni”, 5, “rossi”, 6));

最佳答案

我认为您最好的选择是创建一个包含所有这些字段(包括 Location)的类,然后为它们使用合适的 Collection,例如ArrayList.

List<LocationData> locations = new ArrayList<>();

然后在您的自定义 LocationData 类中使用 getter/setter 对来获取您想要存储的每个字段。

以自定义类为例:

public class LocationData {
//Name these appropriately! I don't know what they're for.
private Location location;
private String string1;
private int num1;
private String string2;
private int num2;
private String string3;
private String string4;

//Constructor
public LocationData(Location loc, String s1, int n1, String s2, int n2, String s3, String s4) {
location = loc;
//And so on for each field
...
}

//One pair of methods for each field
public Location getLocation() {
return location;
}
public void setLocation(Location loc) {
location = loc;
}

关于java - 异构数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37726400/

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