2016-10-02 68 views
1

當我將實體對象添加到我的ArrayList(這裏稱爲實體)時,存在問題。每個實體對象都有一個長ID,int x位置和y位置當添加對象時,Java ArrayList大小變得很大

首先我檢查列表是否爲空,它應該在開始位置。如果我添加第二個實體對象,我檢查對象的ID是否存在,如果是,則更新實體對象的位置。如果該對象不存在,則應該添加該對象。

我的問題是,ArrayList的大小變得巨大,我不知道如何解決它。

以下所有代碼都位於持續運行的update()方法中。

/** 
    * Method that checks if the entity exist or not. 
    * @param ent - The Entity that should be updated or added. 
    */ 
public void checkEntity(Entity ent){ 
    if(entities.isEmpty()){ 
    entities.add(ent); 
    } 
    else{ 
    for(ListIterator<Entity> li = entities.listIterator(); li.hasNext();){ 
     Entity next = li.next(); 
    if(next.getID() == ent.getID()){ 
//  System.out.println("id: " + next.getID() + " xPos: " + next.getXPos() + " yPos: " + next.getYPos() + " type: " + next.getType()); 
     next.setXPos(xPos); 
     next.setYPos(yPos); 

    } 
    else{ 
     li.add(ent); 
    } 
    System.out.println(entities.size()); 
    } 
} 
+0

定義「巨大」。 –

+0

大約20000+,當它應該是2的大小。 –

+0

只要與迭代器中的項目不匹配,您的循環就會添加該項目。只有當* no *項與迭代器中的項匹配時纔想添加項。 – Eric

回答

3

的問題是,您要添加新條目到每一個你發現它不具有相同的ID入口時刻列表...您的通話add你的循環,它不應該是。

基本上,你應該是這樣的:

public void checkEntity(Entity entity) { 
    for (Entity candidate : entities) { 
     if (candidate.getID() == entity.getID()) { 
      candidate.setXPos(entity.getXPos()); 
      candidate.setYPos(entity.getYPos()); 
      // Found a matching entity, so we're done now. 
      // This is important, so we don't add the entity again. 
      return; 
     } 
    } 
    // Haven't found it, so add it to the list 
    entities.add(entity); 
} 

請注意,這是怎麼回事,如果你增添不少實體是非常低效的。從實體ID到實體的映射會更加高效......然後,您不必每實體實體時間檢查

+0

啊,現在我明白了這個問題。非常感謝你的幫助。 –