我认为这些都是基础知识。
我创建了 3 个这样的对象:
for (int j = 1; j < 4; j++) {
int parkingSlot= 1 + rd.nextInt(3);
AircraftCarrier ac= new AircraftCarrier (fc, j, parkingSlots, parkingSlots);
}
基于 AircraftCarrier 类(它的构造函数):
public AircraftCarrier (FlightControl fc, int idC, int parkingSlots, int freeParkingSlots) {
this.kontrolaLotow = fc;
this.id = idC;
this.ps = parkingSlots;
this.fps = freeParkingSlots;
}
所以我有 3 艘航空母舰,对吧?假设我需要更改 id =2 的运营商的 freeParkingSLots 值。我该怎么做?
最佳答案
您创建了三个实例,但由于您没有维护对其中任何一个实例的引用,因此您不再拥有它们。它们已被送去垃圾收集。
您需要将每个实例存储在某个集合中以供以后访问。
List<AircraftCarrier> myList = new ArrayList<AircraftCarrier>();
for (int j = 1; j < 4; j++) {
int parkingSlot= 1 + rd.nextInt(3);
AircraftCarrier ac= new AircraftCarrier (fc, j, parkingSlots, parkingSlots);
myList.add(ac);
}
关于java - 为指定对象设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7406884/