Search code examples
javalinked-listindexof

Change LinkedList elements position


I'm supposed to complete a class named "substitute" that can change elements of a LinkedList between them. I've been trying to figure this on my own but I'm kinda new to programming and I wasn't able to find the answer, I would be grateful if someone could help me. Thanks in advance.

I'm given this code which I cannot change, only write between the brackets:

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

I'm also supposed to pass this JUnit5 test:

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


Solution

  • The LinkedList Class in Java has methods that can help you complete this problem. With the index found in the position, you can call the remove() or set() function to help complete your code.

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