我正在尝试遍历两个ArrayList(分别称为sceneObjects和animationSceneObjects),并根据名称字段将二者匹配。这是我的代码:

Iterator<AnimationObject> itr = animationObjects.iterator();
Iterator<SceneObject> itrMain = sceneObjects.iterator();

while (itr.hasNext()) {
            AnimationObject object = itr.next();
            //Remove the word node from the animation object name so it matches main object name.
            String  tmpString = object.animationobjectName.replace("node-", "");
            System.out.println("Animation Object name is" +tmpString);
            while (itrMain.hasNext()) {
                SceneObject objectMain = itrMain.next();
                System.out.println("Scene Object name is" +objectMain.objectName);
                if (tmpString.equals(objectMain.objectName)) {
                    System.out.println("Animation Object matched to main object array" +tmpString);
                    objectMain.animations = object.animationData;
                    objectMain.hasAnimations = true;
                }
            }
        }


问题在于代码无法按预期工作-它仅将itr迭代器中的第一项与itrMain迭代器的值进行比较。

谁能发现我错了?

谢谢。

最佳答案

您必须在每次运行内部循环之前重置itrMain,否则-第一次耗尽迭代器后-永远不会调用内部循环。

您可以通过在到达内部循环之前使用sceneObjects.iterator()重新分配它来进行操作,或者使用增强的for-each loop

Iterator<AnimationObject> itr = animationObjects.iterator();

while (itr.hasNext()) {
            Iterator<SceneObject> itrMain = sceneObjects.iterator();
       //    ^
       //   reassigning itrMain each iteration of the outer loop

            AnimationObject object = itr.next();
            //Remove the word node from the animation object name so it matches main object name.
            String  tmpString = object.animationobjectName.replace("node-", "");
            System.out.println("Animation Object name is" +tmpString);
            while (itrMain.hasNext()) {
                SceneObject objectMain = itrMain.next();
                System.out.println("Scene Object name is" +objectMain.objectName);
                if (tmpString.equals(objectMain.objectName)) {
                    System.out.println("Animation Object matched to main object array" +tmpString);
                    objectMain.animations = object.animationData;
                    objectMain.hasAnimations = true;
                }
            }
        }

10-08 13:30