-1

How can I remove the specified item from this set if it is present? Return true if the set is modified or false if it is not.

Currently, everything works except the remove() method.

import java.util.Iterator;

public class Set300<T> implements Iterable<T> {

  private Bag<T> bag = new Bag<T>(); 

  public boolean contains(T item) {
      for (T i : bag){
          if (i.equals(item)) return true;
      }
      return false;
  }

  public boolean add(T item) {
      if (contains(item)){
          return false;
      }
      else{
          bag.add(item);
          return true;
      }
  }

  public boolean remove(T item) {
      if (contains(item)){
          return false;
      }
      else{
          Iterator <T> i = bag.iterator();
          while (i.hasNext() == true)

              if (i.next().equals(item));{
                  i.remove(item);
              }
          return true;
      }
  }

  public Iterator<T> iterator() {
      return bag.iterator();
    }
}

The remove() method should return false if the bag does NOT contain the item; otherwise, remove it. It does not return true or false, nor does it remove a number from the set

sqrd
  • 1
  • 3

1 Answers1

0

I think there is a mistake in code you have written. Your remove() is checking the existence of an item in set, if it finds that item them it is returning false instead of removing it. Try replace your remove() with:

public boolean remove(T item) {
  if (contains(item)){
      Iterator <T> i = bag.iterator();
      while (i.hasNext() == true)

          if (i.next().equals(item)){
              i.remove(item);
          }
      return true;

  }
  else{
      return false;
  }
Ravi Chhatrala
  • 324
  • 4
  • 14
  • Thank you for simplifying my code! However, I receive this error when I try running it: "Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method remove() in the type Iterator is not applicable for the arguments (T)" – sqrd Feb 03 '15 at 06:13
  • You should check the parameter you are passing here in remove method. And refer these questions please: [http://stackoverflow.com/questions/13888663/method-in-the-type-is-not-applicable-to-the-arguments] (http://stackoverflow.com/questions/13888663/method-in-the-type-is-not-applicable-to-the-arguments) and [http://stackoverflow.com/questions/12664571/arraylistentity-bikeshoprepair-is-not-applicable-for-the-arguments-double-do] (http://stackoverflow.com/questions/12664571/arraylistentity-bikeshoprepair-is-not-applicable-for-the-arguments-double-do) – Ravi Chhatrala Feb 03 '15 at 06:35