如何将数组列表值与先前值进行比较并避免 IndexOutOfBoundException

How to compare array list value with previous value and avoid 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

来自评论的回答: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) { 布尔结果 = 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;

}