Reputation: 619
This is my list:
List<JiraProjectDetails> projlist = new ArrayList<JiraProjectDetails>();
and i want to fill this list through the following code:
JiraProjectDetails jiraProj = new JiraProjectDetails();
JiraTasks jiraObj = new JiraTasks(glb.getSysProps().getProperty("JIRA_SOAP_USER"),
glb.getSysProps().getProperty("JIRA_SOAP_USER_PWD"),
glb.getSysProps().getProperty("JIRA_BASE_URL"));
RemoteProject r[] = jiraObj.getJiraProjects();
if (r != null){
for (int i = 0; i < r.length; i++) {
jiraProj.setProjectID(r[i].getId());
jiraProj.setProjectDesc(r[i].getDescription());
jiraProj.setProjectKey(r[i].getKey());
jiraProj.setProjectName(r[i].getName());
jiraProj.setURL(r[i].getUrl());
projlist.add(i,jiraProj);
System.out.println("Jira Projects in loop: " + r[i].getName());
}
}
Now, the values that im setting in jiraProj
are correct, but when i fill my projlist
through the add function, it fills all the list with just one value.
How can I solve this?
Upvotes: 0
Views: 66
Reputation: 26067
Create new instance of JiraProjectDetails jiraProj = new JiraProjectDetails();
inside loop instead of outside the loop.
JiraProjectDetails jiraProj = null;
JiraTasks jiraObj = new JiraTasks(glb.getSysProps().getProperty("JIRA_SOAP_USER"),glb.getSysProps().getProperty("JIRA_SOAP_USER_PWD"),glb.getSysProps().getProperty("JIRA_BASE_URL"));
RemoteProject r[] = jiraObj.getJiraProjects();
if(r!=null){
for (int i = 0; i < r.length; i++) {
jiraProj = new JiraProjectDetails();
jiraProj.setProjectID(r[i].getId());
jiraProj.setProjectDesc(r[i].getDescription());
jiraProj.setProjectKey(r[i].getKey());
jiraProj.setProjectName(r[i].getName());
jiraProj.setURL(r[i].getUrl());
projlist.add(i,jiraProj);
System.out.println("Jira Projects in loop: " + r[i].getName());
}
Upvotes: 1
Reputation: 393831
You have to create a new JiraProjectDetails
instance in each iteration of the loop.
if(r!=null){
for (int i = 0; i < r.length; i++) {
JiraProjectDetails jiraProj = new JiraProjectDetails();
jiraProj.setProjectID(r[i].getId());
jiraProj.setProjectDesc(r[i].getDescription());
jiraProj.setProjectKey(r[i].getKey());
jiraProj.setProjectName(r[i].getName());
jiraProj.setURL(r[i].getUrl());
projlist.add(i,jiraProj);
System.out.println("Jira Projects in loop: " + r[i].getName());
}
Otherwise, you are changing the properties of the same object again and again, and since the same object is added to the list again and again, all the elements in the list will have the same values.
Upvotes: 4