设置指定对象的值

时间:2011-09-13 18:47:25

标签: java constructor

我认为那些是细菌。

我创建了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值。我该怎么做?

4 个答案:

答案 0 :(得分:4)

您创建了三个实例,但由于您没有保留对其中任何实例的引用,因此您不再拥有它们。他们被送去垃圾收集。

您需要将每个实例存储在某个集合中以供以后访问。

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

答案 1 :(得分:1)

您必须将运营商存储在一个数组中:

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

现在您可以访问它们了:

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

答案 2 :(得分:1)

您创建了每个实例,但无处保存。因此在循环之后,对象“消失”了。 使用

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

由于您已将id 2分配给第二个元素,因此您现在可以使用carriers.get(1)访问它(get(0)将为您提供第一个元素。)

答案 3 :(得分:1)

您必须将运营商“放置”到某处,以便以后可以访问它们:

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;