1

I am trying to remove the StringBuilder object from an ArrayList, but I'm unable to do that. If I pass this line al.remove("haiti"); that's a string object and is not equals to the StringBuilder and it returns to false. I tried with al.remove(new StringBuilder("haiti")), but that doesn't work as well. Can anyone help?

import java.util.*;

public class HelloWorld {
    public static void main(String[] args) {
        List<StringBuilder> al = new ArrayList<>();
        al.add(new StringBuilder("3")); // [3]
        al.add(new StringBuilder("haiti")); // [3, haiti]
        System.out.println(al); // [3, haiti]
        System.out.println(al.remove(new StringBuilder("haiti")));
        // false, but I want true XD

        System.out.println(al); // Actual [3, haiti], Expected: [3]
    }
}
Daniel Widdis
  • 8,424
  • 13
  • 41
  • 63
Vam
  • 123
  • 4

3 Answers3

3

The purpose of StringBuilder is to be a temporary object for constructing a String in several steps. It does not override equals and hashCode, so no two StringBuilder instances will be equal, even if they have the same contents (which can be changed in each). The only ways to remove one from a List are by index or by passing the reference to the same object itself.

That said, putting StringBuilder into a list like this doesn't make much sense; StringBuilder usually only lives inside a single method, then its toString() result is returned. You probably should be handling your data in an entirely different manner.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
1

As chrylis said, the usage of StringBuilder is not understood in this case.

I guess you would use String instead of StringBuilder. Something like:

public class HelloWorld {
    public static void main(String[] args) {
        List<String> al = new ArrayList<>();
        al.add("3"); // [3]
        al.add("haiti"); // [3, haiti]
        System.out.println(al); // [3, haiti]
        System.out.println(al.remove("haiti"));

        System.out.println(al);
    }
}

What do you think?

Community
  • 1
  • 1
javadev
  • 688
  • 2
  • 6
  • 17
1

Since Java 8 you can use removeIf method:

List<StringBuilder> al = new ArrayList<>();
al.add(new StringBuilder("3"));
al.add(new StringBuilder("haiti"));

System.out.println(al); // [3, haiti]
// if the string contained in StringBuilder is equal to the
// desired string, then remove this element from the list
System.out.println(al.removeIf(sb -> sb.toString().equals("haiti"))); // true
System.out.println(al); // [3]

See also: How to use StringBuilder inside the reduce method in java 1.8?