以下是我在方法内构造对象的方法:
//创建类之后
public static ArrayList<Object> old_devicelist = new ArrayList<Object>();
//方法内部
Date date = new Date();
long time = date.getTime();
Integer opened = 0;
String deviceId = "";
String dev_rssi = "";
Object[] MyObject = new Object[]{time, opened, deviceId, dev_rssi};
old_devicelist.add(MyObject);
现在,我想循环遍历该 ArrayList 并访问其中的一些元素(请注意,deviceId 在某些时候可能包含一个对象,我想访问它的 id 字段),然后我想像这样使用它们这个,例如。 :
if(device.id == 33){
//do something...
}
最佳答案
您正在使用类型为 Object 的数组,然后将这些对象数组存储到列表中。这使得以后检索信息变得困难。
考虑这个:
public static List<Device> DEVICES = new ArrayList<>();
class Device {
Date date;
long time;
Integer opened;
String deviceId;
String deviceRssi
Device(Date date, Integer opened, String deviceId, String deviceRssi) {
this.date = date;
this.time = date.getTime();
this.opened = opened;
this.deviceId = deviceId;
this.deviceRssi = deviceRssi;
}
}
Device first = new Device(
new Date(),
0,
"",
"");
DEVICES.add(first);
System.out.println(DEVICES.get(0).deviceId);
...
for (Device device : DEVICES) {
if (device.deviceId.equals("33)) {
// ...
}
}
我建议不要使用太多静态/全局变量并阅读有关 Java 命名约定的内容。
关于java - 如何访问和读取一个对象的子对象的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60419958/