Вопрос

public class ServersList {

    private Host host;
    private Server server;
    private InfoList infoList;
    private List<AbcInformation> abcInformation;

    @XmlElement(name = "Host")
    @JsonProperty("Host")
    public Host getHost() {
        return this.host;
    }

    //Get Set functions for all object
}

We have the above class. It contains some object of other classes and get/set methods as shown above. We are parsing an XML file and creating an array of ServersList class. For example,

ServersList[] serversArray = new ServersList[count];
for (int index = 0; index < count; index++) {
  serversArray[index] = new ServersList();

  serversArray[index].setInfoList(serConfig
            .getInfoList());
  serversArray[index].setHost(serConfig
            .getHost());
  serversArray[index].setServer(serConfig
            .getServer());

  serversArray[index].getHost().setCid(
    listResponse.getHost().get(index).getCid());
  serversArray[index].getHost().setCName(
    listResponse.getHost().get(index).getCname());
  serversArray[index].getHost()
      .setCurrentName(listResponse.getHost().get(index)
     .getCurrentName());
  serversArray[index].getHost().setHostName(listResponse.getHost().
     get(index).getName());
  serversArray[index].getHost().setHostUuid(
     listResponse.getHost().get(index).getId());

}

Our problem is after the for loop all values of the serversArray array will be same (may be with last element in the xml). While debugging I understand that, every iteration the value of every rows are changed the values of current row. Can you suggest a solution for this?

Это было полезно?

Решение 2

Finally I found the solution. I have added copy constructors for the following classes

ServersList, Host, Server, InfoList, AbcInformation

Другие советы

Try doing this, should work.

public static void main(String[] args) {
        ServersList sList=null;
        int count=10;
        ServersList[] serversArray = new ServersList[count];
        for (int index = 0; index < count; index++) {
          sList = new ServersList();
          sList.setHost(....);
          //..........other setter...........
          serversArray[index] = sList;
        }

        for (ServersList serversList : serversArray) {
            System.out.println(serversList.getHost());
        }
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top