首页 > 解决方案 > 更改 LinkedList 元素的位置

问题描述

我应该完成一个名为“substitute”的类,它可以在它们之间更改 LinkedList 的元素。我一直试图自己解决这个问题,但我对编程有点陌生,我无法找到答案,如果有人能帮助我,我将不胜感激。提前致谢。

我得到了无法更改的代码,只能写在括号内:

import java.util.Iterator;
import java.util.LinkedList;

public class Device implements Iterable<String>{
    private static int numDevices=0; //device counter... static atribute
    private String name;
    private int id;
    protected LinkedList<String> words; 

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());


        return true;
    }

我也应该通过这个 JUnit5 测试:

assertTrue(d1.substitute("amigo", "perla")); //returns true because the word amigo exists --> returns true
  
        assertFalse(d1.substitute("amigo", "perla")); //the word amigo does not exist --> returns false
 
        assertTrue(d1.substitute("estamos", "estas"));
         
        assertTrue(d1.substitute("que", null)); //remove the word que
        assertTrue(d1.substitute("tal", null)); //remove the word tal

标签: javalinked-listindexof

解决方案


Java 中的 LinkedList 类有一些方法可以帮助你完成这个问题。使用在该位置找到的索引,您可以调用 remove() 或 set() 函数来帮助完成您的代码。

public boolean substitute(String word1, String word2) {
    int position = this.words.indexOf(word1.toLowerCase());
    if(position == -1) {
        return false; // index of -1 means the word wasn't found in the list, return false
    }
    if(word2 == null) { // remove item if word2 is null as indicated by tests
        words.remove(position);
    } else {
        words.set(position, word2); // set word2 at the position word1 was found at
    }
    return true;
}

推荐阅读