【问题标题】:Change LinkedList elements position更改 LinkedList 元素的位置
【发布时间】:2021-09-14 17:22:56
【问题描述】:

我应该完成一个名为“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

【问题讨论】:

    标签: java linked-list indexof


    【解决方案1】:

    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;
    }
    

    【讨论】:

    • 非常感谢,它成功了,最后很简单:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2014-08-31
    • 1970-01-01
    • 2012-09-03
    • 2014-09-16
    相关资源
    最近更新 更多