【问题标题】:Java ArrayList size gets enormous when adding objects添加对象时,Java ArrayList 大小变得巨大
【发布时间】:2017-02-10 16:45:58
【问题描述】:

当我将实体对象添加到我的 ArrayList(这里称为实体)时,我遇到了问题。每个 Entity-object 都有一个长 ID,int x-position 和 y-position

首先我检查列表是否为空,它应该在开始时。如果我添加第二个实体对象,我会检查对象的 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());
   }
 }

【问题讨论】:

  • 定义“巨大”。
  • 大约 20000+ 当它应该像 2 大小时。
  • 只要与迭代器中的项不匹配,您的循环就会添加该项。仅当 no 项与迭代器中的项匹配时,您才想添加该项。

标签: java arraylist iterator size


【解决方案1】:

问题在于,您正在向列表中添加一个新条目每次您找到一个不具有相同 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 到实体的映射会更有效...然后您不需要检查每个实体每次时间。

【讨论】:

  • 啊,现在我明白了这个问题。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2013-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-17
  • 1970-01-01
相关资源
最近更新 更多