首页 > 解决方案 > 如何将数组列表值与前一个值进行比较并避免 IndexOutOfBoundException

问题描述

我有一些用 Java 编写的 Selenium 测试,我循环遍历 Array List 对象,我尝试根据这些规则为每个 UI 元素输入计算输入数据:

所以我有一个循环:

 for (int i = 0; i < testDataML.size(); i++) {
            ...
            inputMLData(i);
            CommonMethods.clickCalculate(path, outputPath, i);
            ...
    }

然后在函数 inputMLData 中,我们为每个 UI 元素重复这些块:

        if (i == 0) {
            if (!testDataML.get(i).In_VersionID.isEmpty())
                setInputElementPathML(false, "VersionID", testDataML.get(i).In_VersionID);
        } else if (!testDataML.get(i).In_VersionID.equals(testDataML.get(i - 1).In_VersionID))
            setInputElementPathML(false, "VersionID", testDataML.get(i).In_VersionID);

而这个逻辑目前是基于我之前写的这两点工作的。但基本上我必须有两个条件 - if (i==0)然后使用else if以避免在第一次循环迭代时获得 IndexOutOfBoundException 。在这两个条件之后,我调用了相同的函数。所以问题是我怎样才能避免这种异常?我不想使用 try 块,因为它会导致基本相同数量的代码。整个 if 逻辑我可以转移到另一个函数,但我仍然必须为该函数提供参数 testDataML.get(i - 1).In_VersionID

标签: javafor-looparraylistindexoutofboundsexception

解决方案


评论回复:testDataML.get( (i ==0)? i : i-1).In_VersionID。inputMLData 中的最终结果如下所示:

if (CommonMethods.isNewInput(testDataML.get(i).In_VersionID, testDataML.get((i ==0)? i : i-1).In_VersionID, i, false)) {
            setInputElementPathML(false, "VersionID", testDataML.get(i).In_VersionID);
        }

isNewInput 现在看起来像这样:

public static boolean isNewInput (String currentValue, String previousValue, int i, boolean ignoreCase) { boolean result = false;

if (i==0&&!currentValue.isEmpty()) {
    return true;
}

if (ignoreCase) {
    if (!currentValue.equalsIgnoreCase(previousValue)) {
        result = true;
    }
}
else {
    if (!currentValue.equals(previousValue)) {
        result = true;
    }
}
return result;

}


推荐阅读