2014-01-14 33 views
0

所以,在我的代碼中,我得到一個組件列表,迭代組件,在每個組件內部獲得組件的維護並遍歷它們。問題是,該項目被beying替換,而不是重新創建,如我所願:奇怪的Java迭代器項目被取代

List<ComponentRelation> componentRelations = getComponentRelations(); 

List<MaintenanceRequired> allMaintenancesRequired = new ArrayList<MaintenanceRequired>(); 

for (Iterator<ComponentRelation> iterator = componentRelations.iterator(); iterator.hasNext();) { 
    ComponentRelation componentRelation = iterator.next(); 
    System.out.println("Getting maintenances from "+componentRelation.getComponent().getName()+" at position "+ComponentInstallationPosition.getPositionString(componentRelation.getInstallationPosition())); 
    for (Iterator<MaintenanceRequired> iterator2 = maintenancesDAO.getRequiredMaintenancesByComponentRelation(componentRelation).iterator(); iterator2.hasNext();) { 
     MaintenanceRequired maintenanceRequired = (MaintenanceRequired) iterator2.next(); 
     maintenanceRequired.setMaintenancePerformedOnComponent(omponentRelation); 
      allMaintenancesRequired.add(maintenanceRequired); 
    } 
} 

因此,println的是正確的,但該項目內:

public void setMaintenancePerformedOnComponent(ComponentRelation maintenancePerformedOnComponent) { 
    if (this.maintenancePerformedOnComponent!=null) 
     System.out.println("SETTING "+ComponentInstallationPosition.getPositionString(this.maintenancePerformedOnComponent.getInstallationPosition())+" to "+ComponentInstallationPosition.getPositionString(maintenancePerformedOnComponent.getInstallationPosition())); 
    else System.out.println("SETTING "+ComponentInstallationPosition.getPositionString(maintenancePerformedOnComponent.getInstallationPosition())); 
    this.maintenancePerformedOnComponent = maintenancePerformedOnComponent; 
} 

所以印刷說:

"getting maintenances from X-1, position 1" 
"SETTING 1" 
"SETTING 1" 
"SETTING 1" 
"SETTING 1" 
"SETTING 1" 
"getting maintenances from X-2, position 2" 
"SETTING 1 to 2" 
"SETTING 1 to 2" 
"SETTING 1 to 2" 
"SETTING 1 to 2" 
"SETTING 1 to 2" 

那麼,爲什麼他會設置1到2,如果它是另一個對象?

正如約翰問,我做什麼吧:

create empty list of items Y; 

get list of items X; 

iterator of list of items X { 
    get from database all Y inside X and iterate{ 
     set iterated Y that he has a position K; 
     put iterated Y inside created initially empty list of Y; // first line 
    } 
} 
+1

靜態類變量? – turbo

+1

如果你想出一個簡短但完整的例子來證明這個問題,理想情況是這個例子中沒有那麼冗長和明確的商業特定名稱,那麼它會更容易幫助你。 –

+0

不是靜態的..現在增加更簡單的例子 –

回答

0

採取仔細看看:

System.out.println("SETTING "+ComponentInstallationPosition.getPositionString(this.maintenancePerformedOnComponent.getInstallationPosition())+" to "+ComponentInstallationPosition.getPositionString(maintenancePerformedOnComponent.getInstallationPosition())); 

你不要引用當地maintenancePerformedOnComponentthis.maintenancePerformedOnComponent

+0

是的,正如解釋過的那樣,這是在對象中的設置者。感謝您的回覆,還有其他想法? –