如何自动化实现:检查列表仅第5位为空其余元素均非空?
嘿,我看到你现在的代码逻辑完全搞反啦!咱们先理清楚核心需求:要检查的是只有第5个元素(对应列表索引4,因为Java列表是0开始计数)是空字符串,其余所有位置的元素都非空,但你当前的条件刚好和需求相反——你现在判断的是除了索引5之外全是空,这肯定达不到目的呀。
下面给你两种更合理、可自动化复用的实现方案:
优化后的检查方案
方案1:通用遍历法(推荐,扩展性强)
这种方法不光适用于10个元素的列表,以后如果列表长度调整,或者需要检查其他位置为空,只要修改少量参数就行,代码更简洁易维护:
public boolean checkOnlyTargetElementEmpty(List<String> actualList) { // 先校验列表长度是否符合预期(这里固定为10) if (actualList.size() != 10) { return false; } int targetEmptyIndex = 4; // 要检查的唯一空元素的索引(对应第5个元素) for (int i = 0; i < actualList.size(); i++) { String currentElement = actualList.get(i); // 分两种情况判断:目标索引必须为空,其他索引必须非空 if (i == targetEmptyIndex) { if (!currentElement.isEmpty()) { return false; } } else { if (currentElement.isEmpty()) { return false; } } } // 所有检查都通过,返回true return true; }
方案2:固定长度直接判断(适合列表长度永远是10的场景)
如果确定列表长度不会改变,也可以写更直接的条件判断,比你原来的写法简洁且逻辑正确:
public boolean checkOnlyFifthElementEmpty(List<String> actualList) { return actualList.size() == 10 && actualList.get(4).isEmpty() && !actualList.get(0).isEmpty() && !actualList.get(1).isEmpty() && !actualList.get(2).isEmpty() && !actualList.get(3).isEmpty() && !actualList.get(5).isEmpty() && !actualList.get(6).isEmpty() && !actualList.get(7).isEmpty() && !actualList.get(8).isEmpty() && !actualList.get(9).isEmpty(); }
调用示例(实现需求的返回逻辑)
拿到上面方法的返回结果后,就可以按照需求返回指定文本了:
// 假设你的列表是actualList if (checkOnlyFifthElementEmpty(actualList)) { return "符合要求的指定文本"; } else { return "不符合要求的指定文本"; }
这样就能完全自动化完成检查,不需要手动逐个判断啦~
内容的提问来源于stack exchange,提问作者Andriy Skyba
相关产品推荐
相关产品推荐

