开发者

Setting value for specified object

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开发者_JS百科, 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?


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.

 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);
}


You have to store the Carriers in an array:

AircraftCarrier[] carriers = new AircreaftCarrier[3];
for (int j = 0; j < carriers.length; j++) {
    int parkingSlot= 1 + rd.nextInt(3);
    AircraftCarrier ac = new AircraftCarrier (fc, j + 1, parkingSlots, parkingSlots);
    carriers[i] = ac;
}

Now you are able to access them:

carriers[1].fps = 6; // You wanted id=2. Since we count from zero in Java, use 1


You created each of the instances, but saved them nowhere. So after the loop, the objects are "gone". Use

List<AircraftCarrier> carriers = new ArrayList<AircraftCarrier>();
for (int j = 1; j < 4; j++) {
  int parkingSlot = 1 + rd.nextInt(3);
  AircraftCarrier ac = new AircraftCarrier (fc, j, parkingSlots, parkingSlots);
  carriers.add(ac);
}

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:

Map<Integer, AircraftCarrier> carriers = new HashMap<Integer, AircraftCarrier>();

for (int j = 1; j < 4; j++) {
    int parkingSlot= 1 + rd.nextInt(3);
    AircraftCarrier ac= new AircraftCarrier (fc, j, parkingSlots, parkingSlots);
    carriers.put(j, ac);
}

/* update carrier with ID 2 */
carriers.get(2).fps = 1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜