1

I created a simple method to remove all instances of the desired string from the ArrayList. When checking the method I realized that I was supposed to use .equals() when comparing the value in the ArrayList to the target instead of using "==". Why does "==" work when .equals() should be used to compare the two string values?


public class MyProgram extends ConsoleProgram
{
    public void run()
    {

        ArrayList<String> pokemon = new ArrayList<String>();
        pokemon.add("Beedrill");

        pokemon.add("Castform");
        pokemon.add("Charmander");
        pokemon.add("Charmander");
        pokemon.add("Ditto");

        System.out.println(pokemon);

        remove(pokemon, "Charmander");

        System.out.println(pokemon);
    }

    public static void remove(ArrayList<String> list, String target){
       for(int i = list.size()-1; i > 0; i--){
           if(list.get(i) == target){
               list.remove(i);
           }
       }
    }


}

Here's a picture of the working code on sololearn.com.

Working code on sololearn.com

ApollosB
  • 11
  • 2
  • 1
    Because you are using `String`-constants. `System.out.println("Hello" == "Hello");` will return `true`, because the compiler constructs a single `String`-object, holding the value `"Hello"` and replaces it for every occurence of `"Hello"` in the code. I gave a more in-depth explanation in [this answer](https://stackoverflow.com/questions/59592175/using-in-java/59592252#59592252). – Turing85 Jan 20 '20 at 19:44
  • 1
    Because two string literals in Java code are guaranteed to be the same String object. – JB Nizet Jan 20 '20 at 19:44
  • 1
    Does this answer your question? [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – bakero98 Jan 20 '20 at 19:48
  • 1
    @bakero98 no, this is not a duplicate. OP is well aware that `.equals(...)` should be used. – Turing85 Jan 20 '20 at 19:49
  • It actually is a duplicate. While the title may be misleading, the content of the linked duplicate explains string-interning as well. If an answer explains OPs question, its a duplicate, even if the original question was different (that is explained somewhere in a popular meta question). – Zabuzard Jan 20 '20 at 19:53
  • 1
    @Zabuza, prior to asking my question I had already viewed the linked question. However, I didn't know that what was going on in the compiler was string - interning. Not until Turing85 responded did I realize that the answer was similar to answers in the linked question. – ApollosB Jan 20 '20 at 20:13
  • Fair enough, no worries. – Zabuzard Jan 20 '20 at 20:28

0 Answers0