2

I was given Bag class like this

    import java.util.Iterator;
    import java.util.NoSuchElementException;

    public class Bag<Item> implements Iterable<Item> {

    private int N;               // number of elements in bag
    private Node<Item> first;    // beginning of bag

    // helper linked list class
    private class Node<Item> {
    private Item item;
    private Node<Item> next;
    }

    /**
    * Initializes an empty bag.
     */
    public Bag() {
    first = null;
    N = 0;
    }

    /**
     * Is this bag empty?
    * @return true if this bag is empty; false otherwise
     */
    public boolean isEmpty() {
    return first == null;
    }

    /**
     * Returns the number of items in this bag.
     * @return the number of items in this bag
     */
    public int size() {
    return N;
    }

    /**
     * Adds the item to this bag.
     * @param item the item to add to this bag
     */
    public void add(Item item) {
    Node<Item> oldfirst = first;
    first = new Node<Item>();
    first.item = item;
    first.next = oldfirst;
    n++;
}

    public void remove(Item item){ 
    // currentNode is the reference to the first node in the list and to the Item
    Node<Item> currentNode = first; 
    // if items equals the first node in the list, then first = currentNode.next which will make the first item 
    Node<Item> temp = currentNode;
    while(temp.next != null){
        temp = currentNode;
        if(item.equals(currentNode.item)){
            currentNode = currentNode.next;
            temp.next = currentNode;
            break;
        }else{
            currentNode = currentNode.next;
        }
    }
    N--; 
}

/**
 * Returns an iterator that iterates over the items in the bag in arbitrary order.
 * @return an iterator that iterates over the items in the bag in arbitrary order
 */
public ListIterator<Item> iterator()  {
    return new ListIterator<Item>(first);  
}

// an iterator, doesn't implement remove() since it's optional
private class ListIterator<Item> implements Iterator<Item> {
    private Node<Item> current;

    public ListIterator(Node<Item> first) {
        current = first;
    }

    public boolean hasNext()  { return current != null;                     }
    public void remove()      { throw new UnsupportedOperationException();  }

    public Item next() {
        if (!hasNext()) throw new NoSuchElementException();
        Item item = current.item;
        current = current.next; 
        return item;
    }
}

As it can be seen,remove() method is an optional therefore it doesn't include the algorithm.

I wrote the remove method like this:

public void remove(Item item)      { 
        Node<Item> currentNode = (Node<Item>) first;
        Node<Item> previousNode = null;
        while(currentNode != null){
            if(item.equals(currentNode.item)){
                if(previousNode  == null) {
                  first = (Node<Item>) currentNode.next;
                }
                else {
                  previousNode.next = currentNode.next;
                }
                n--;
            }
            else {
              previousNode = currentNode;
            }
            currentNode = currentNode.next;
        }

    }

However,

first = (Node<Item>) currentNode.next;

this line gives an "Type mismatch:Cannot convert from Bag.Node to Bag.Node" error which confuses me.

What should be done to overcome this error or is there a missing part in my remove method?

efedoganay
  • 133
  • 2
  • 11

2 Answers2

2
public class Bag<Item> implements Iterable<Item> {
  // ...
  private class Node<Item> {
    // ...
  }
  // ...
}

This is defining two distinct type variables, both with the name Item.

If you want instances of Node to use the same type variable as the containing instance of Bag, remove the <Item> on Node:

private class Node {
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • I tried this also but then "private Item item" variable gives an error "Cannot make a static reference to non-static type Item" – efedoganay May 06 '18 at 21:44
  • @FikretEfeDoğanay considering you don't use `static` in this code, I doubt that. I could believe it if if were `private static class Node`. Are you sure this is the exact code you are trying to run? – Andy Turner May 06 '18 at 21:45
  • Yes you are right! I forgot to remove static field in the Node class. Thank you a lot! – efedoganay May 06 '18 at 21:48
0

I overcome this problem in this way.

   public void removeAllOccurences(Item item){ 

   Node<Item> currentNode = first;

   Bag<Item> b = new Bag<Item>();
   Bag<Item> reverseB = new Bag<Item>();

   Node<Item> previous = new Node<Item>();

        if(item.equals(first.item)){

                first = currentNode.next;
                N--;
                currentNode = currentNode.next;
                }

            previous.item = currentNode.item;

            b.add(previous.item);

            currentNode = currentNode.next;

            while(currentNode != null){

                if(item.equals(currentNode.item))
                {
                    previous.item = previous.item;
                        N--;

                } else{

                        previous.item = currentNode.item;
                        b.add(previous.item);

                }


                currentNode = currentNode.next;


            }

            for(Item i: b)
                reverseB.add(i);

        this.first = reverseB.first;

}

If you want to test...

public static void main(String[] args) {

    Bag<Integer> b = new Bag<Integer>();
    Random rm = new Random();

    for(int i =0; i < 10; i++)
        b.add(rm.nextInt(3));

    System.out.println("Bag before removing op: ");
    for(Integer i: b)
        System.out.print(" "+ i);

    System.out.println("\nBag size BEFORE: "+b.size());

    b.removeAllOccurences(2);

    System.out.println("\nBag after removing op: ");
    for(Integer i: b)
        System.out.print(" "+ i);
    System.out.println("\nBag size AFTER: "+b.size());

}

Output removing all occurrences of 2:

 0 2 2 0 1 1 0 0 0 2
Bag size BEFORE: 10

Bag after removing op: 
 0 0 1 1 0 0 0
Bag size AFTER: 7
Kon
  • 4,023
  • 4
  • 24
  • 38