2

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--;
            }
        }
    }
}
4
  • 5
    You forgot to ask a question. Commented Sep 14, 2018 at 20:24
  • 2
    What's the issue? Commented Sep 14, 2018 at 20:24
  • 2
    that accepts an ArrayList of Strings and a target String as two parameters: does your remove method respect these requirements? I only see one parameter. Commented Sep 14, 2018 at 20:25
  • x is empty. Did you mean to pass the x from the main method as a parameter? Commented Sep 14, 2018 at 20:26

1 Answer 1

2

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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.