Object String Array Conflict

1

I have a problem with my program, and that is that I am modifying an arrayString of one of my objects (use positioning because it is an array of objects and each object has an array String initialized with space ""). What I intend to do is, put a value in some position of the obtained arrayString (to an auxiliary-> roomReg = room [0] .getReg ()) is supposed to be empty, I put the value in roomReg [any position] = id & lt ; - it's string and then I set it room [0] .setReg (salaReg)

It is supposed that here I have only modified the arrayString of the room object [0] and it is assumed that the rest of the room objects [from the 1st to the last] follow with an empty arrayString.For according to my program it is not like that, and because every time an arrayString is modified, it is modified in all. so it releases an overflow because the arrayString has 7 positions and the rooms have 10.

public class Visitor extends Thread {

private Semaphore sem;
private String id;
private Room sala[];

public Visitante(String id, Room sala[], Semaphore sem) {
    this.id = id;
    this.sala = sala;
    this.sem = sem;
}

@Override
public void run() {
    String salaReg[];
    String salaRegAnt[];
    boolean listo = true;
    boolean existe = true;
    int j = 0;
    int k = 0;
    int numRan;

    try {

        sem.acquire();
        System.out.println("/////////////////HILO " + id);
        System.out.println("Estoy en sala " + sala[0].getId());
        salaReg = sala[0].getReg();
        System.out.println("Actual");
        for (int m = 0; m < salaReg.length; m++) {
            System.out.printf(salaReg[m] + " | ");
        }
        System.out.println("");
        //System.out.println("----------------------------------------");
        while (listo) {
            if (salaReg[j].equals(" ")) {
                salaReg[j] = id;
                sala[0].setReg(salaReg);
                listo = false;
            } else {
                j++;
            }
        }
        j = 0;
        listo = true;
        numRan = (int) (Math.random() * 2000 + 400);
        Thread.sleep(numRan);

        System.out.println("Museo con " + sala.length + " salas");

        //Empieza desde la posicion 1 ya que la posicion 0 la usé anteriormente
        for (int i = 1; i < sala.length; i++) {
            salaReg = null;
            System.out.println("Soy " + id + "  y estoy en sala " + sala[i].getId());

            salaReg = sala[i].getReg();//Array que se supone que debería estar vacio
            //ya que a cada sala del array de salas
            //se le ha "seteado" un array de tipo String
            //con tamaño 7
            //e inicializada a " "

            salaRegAnt = sala[i - 1].getReg();//este array del anterior objeto(por eso i-1)
            //debería tener 1 sólo dato

            System.out.println("Actual");
            for (int m = 0; m < salaReg.length; m++) {
                System.out.printf(salaReg[m] + " | ");
            }
            System.out.println();

            while (listo) {
                if (salaReg[j].equals(" ")) {//EL PROBLEMA LO DA AQUÍ
                    salaReg[j] = id;
                    sala[i].setReg(salaReg);
                    System.out.println("Antes");
                    for (int m = 0; m < salaRegAnt.length; m++) {
                        System.out.printf(salaRegAnt[m] + " | ");
                    }
                    System.out.println();

                    while (existe) {
                        if (salaRegAnt[k].equals(id)) {
                            salaRegAnt[k] = " ";
                            sala[i - 1].setReg(salaRegAnt);
                            System.out.println("Despues");
                            for (int m = 0; m < salaRegAnt.length; m++) {
                                System.out.printf(salaRegAnt[m] + " | ");
                            }
                            System.out.println();
                            existe = false;
                        } else {
                            k++;
                        }
                    }
                    listo = false;
                } else {
                    j++;
                }
            }
            System.out.println("----------------------------------------");
            j = 0;
            k = 0;
            listo = true;
            numRan = (int) (Math.random() * 2000 + 800);
            Thread.sleep(numRan);
            System.out.println("///////////////////////////////////////");
        }
        sem.release();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Class room

public class Room {

private String id;
private String reg[];

public Room(String id, String reg[]) {
    this.id = id;
    this.reg = reg;
}

public String getId() {
    return id;
}

public String []getReg() {
    return reg;
}

public void setId(String id) {
    this.id = id;
}

public void setReg(String reg[]) {
    this.reg = reg;
}

}

Main Class

Public class Principal {

public static void main(String[] args) {
    final int ROOMS = 10;
    final int VIS = 7;
    final int GROUP = 7;
    Semaphore SEM = new Semaphore(1);

    String reg[] = new String[GROUP];
    Room sala[] = new Room[ROOMS];
    Visitante hiloVisitador[] = new Visitante[VIS];

    //Inicializa reg
    for (int i = 0; i < GROUP; i++) {
        reg[i] = " ";
    }
    for (int i = 0; i < ROOMS; i++) {
        sala[i] = new Room(String.valueOf(i + 1), reg);
    }

    for (int i = 0; i < VIS; i++) {
        hiloVisitador[i] = new Visitante(String.valueOf(i + 1), sala, SEM);
        hiloVisitador[i].start();
    }
    try {
        for (int i = 0; i < VIS; i++) {
            hiloVisitador[i].join();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
   }
}

}

I leave my code for you to launch and observe my problem

    
asked by Geany 18.12.2016 в 15:32
source

1 answer

2

The problem is here:

sala[i] = new Room(String.valueOf(i + 1), reg);

All objects in sala use the same reg in the parameter. Therefore, changing the state in sala[0] is "affected" in the other elements of sala . The "affected" is in quotation marks since that is the normal behavior of the objects.

What you need is to have a different arrangement for each instance of sala . I recommend you rearrange the code like this:

for (int i = 0; i < ROOMS; i++) {
    String reg[] = new String[GROUP];
    for (int i = 0; i < GROUP; i++) {
        reg[i] = " ";
    }
    sala[i] = new Room(String.valueOf(i + 1), reg);
}

According to your last comment, a List<String> could solve it, as long as a different list is assigned to each instance of sala .

    
answered by 18.12.2016 / 16:03
source