-1

I am trying to add "Luis" 3 times to array list and then remove "Luis" so there is only one "Luis". Seems to be a problem with the if.

import java.util.ArrayList;

public class Menu {
    private ArrayList<String> meals;

    public Menu() {
        this.meals = new ArrayList<String>();
    }

    // Implement the methods here
    public void addMeals() {

        this.meals.add("Luis");
        this.meals.add("Luis");
        this.meals.add("Luis");
        for (String container : this.meals) {
            for (int counter = 0; counter < this.meals.size(); counter++) {
                ***if (counter > 1 && this.meals.contains(container)) {
                    this.meals.remove(this.meals.indexOf(container));
                }***
            }
        }
        System.out.println(this.meals);
    }

}
Lsanc274
  • 19
  • 3

1 Answers1

0

An ArrayList can contain duplicates. There are other Java collection classes which can only contain unique elements, such as Set.

I'd suggest you look at the documentation for Set and its implementations, this would likely solve your issue.

acanby
  • 2,936
  • 24
  • 26
  • You are forgetting this is probably assignment, and in assignments the code has to follow crazy rules, just because. Even if there is better way to eliminate the pre-condition altogether before it occurs due to poor design, it has to happen, so you can try to "eliminate" it.. – The Law Oct 22 '15 at 21:36