为指定对象设置值
我认为这些都是基础知识。
我创建了 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 值。我该怎么做?
I assume those are bacics.
I've created 3 objects like this:
for (int j = 1; j < 4; j++) {
int parkingSlot= 1 + rd.nextInt(3);
AircraftCarrier ac= new AircraftCarrier (fc, j, parkingSlots, parkingSlots);
}
Based on class AircraftCarrier (it's constructor):
public AircraftCarrier (FlightControl fc, int idC, int parkingSlots, int freeParkingSlots) {
this.kontrolaLotow = fc;
this.id = idC;
this.ps = parkingSlots;
this.fps = freeParkingSlots;
}
So i have 3 Aircraft Carriers, right? Let's assume I need to change freeParkingSLots value for a carrier with id =2. How do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您创建了三个实例,但由于您没有维护对其中任何一个实例的引用,因此您不再拥有它们。它们已被送往垃圾收集站。
您需要将每个实例存储在某个集合中以供以后访问。
You created three instances but since you didn't maintain the reference to any of them, you no longer have them. They have been sent to garbage collection.
You need to store each instance in some collection for later access.
您必须将运营商存储在数组中:
现在您可以访问它们:
You have to store the Carriers in an array:
Now you are able to access them:
您创建了每个实例,但没有保存它们。所以在循环之后,对象就“消失了”。
使用
由于您将 id 2 分配给了第二个元素,因此您现在可以使用
riers.get(1)
访问它(get(0)
将为您提供第一个元素)。You created each of the instances, but saved them nowhere. So after the loop, the objects are "gone".
Use
Since you assigned id 2 to the second element, you can now access it using
carriers.get(1)
(get(0)
would give you the first element).您必须将载体“放置”在某处,以便稍后可以访问它们:
You must 'place' the carriers somewhere so that you can access them later: