cmark
cmark

Reputation: 35

Removing Strings from Arrays using a submethod JAVA

I need to use the method "remove" that accepts an ArrayList of Strings and a target String as two parameters, and searches and deletes all matched Strings from the ArrayList. For example, calling remove on the ArrayList [“Go”, “Go”, “Go”] and the target String “Go”, would result in an empty ArrayList.

public class Remove {
    public static void main (String [] args) {
        ArrayList<String> x = new ArrayList<>();  
        x.add("Go");
        x.add("Go");
        x.add("Go");
        System.out.println(x);
        remove("Go");
        System.out.println(x);
    }

    public static void remove(String t) {
        ArrayList<String> x = new ArrayList<>();
        for(int i = 0; i < x.size(); i++) {
            if(x.get(i).equals(t)) {
                x.remove(i);
                i--;
            }
        }
    }
}

Upvotes: 2

Views: 107

Answers (1)

Mureinik
Mureinik

Reputation: 311163

The remove method creates a new ArrayList and then attempts to remove a value from it. Instead, you should pass a list to the method. Additionally, using JDK 8's removeIf method would make your code much simpler:

public static void main (String [] args) {
    List<String> x = new ArrayList<>();  
    x.add("Go");
    x.add("Go");
    x.add("Go");
    System.out.println(x);
    remove(x, "Go");
    System.out.println(x);
}

public static void remove(List<String> list, String t) {
    list.removeIf(s -> s.equals(t));
}

Upvotes: 2

Related Questions