You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现LinkedList元素替换删除substitute方法通过JUnit5测试

Java Device类substitute方法实现方案

核心需求

完成Device类中substitute方法,实现LinkedList元素的替换或删除功能,仅可在指定位置补充逻辑,不可修改原有代码框架。

约束规则

  • 禁止使用ListIterator<>
  • 必须使用indexOf()方法
  • 返回规则:待操作的word1存在返回true,不存在返回false
  • 操作规则:传入word2为null时删除对应元素,否则将对应元素替换为word2

补全后的完整方法代码

public boolean substitute(String word1, String word2) {
        //You can't use ListIterator<>
        //You must use indexOf()...
        //incomplete code that I'm not allowed to change ahead:

        int position = this.words.indexOf(word1.toLowerCase());

        // 补充逻辑开始
        if (position < 0) {
            return false;
        }
        if (word2 == null) {
            words.remove(position);
        } else {
            words.set(position, word2);
        }
        // 补充逻辑结束
        return true;
    }

实现说明

  1. 原有代码已经通过indexOf()获取了word1小写形式在链表中的索引,元素不存在时indexOf()会返回-1,此时直接返回false即可匹配不存在的测试场景
  2. 索引合法时判断word2是否为null:
    • 为null时调用LinkedList的remove(int index)方法删除对应位置元素
    • 不为null时调用LinkedList的set(int index, E element)方法替换对应位置元素
  3. 操作完成后返回true,匹配元素存在的测试场景
    该实现可完全通过给出的JUnit5测试用例,符合所有约束要求。

内容的提问来源于stack exchange,提问作者MorenDess

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:48:00