我是“ Java新手”,所以请耐心等待我:)
我需要创建一个包含异构字段的特殊结构。
我正在从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;
}