1. Engineering
  2. Computer Science
  3. write a uniquebag container this is a lot like a...

Question: write a uniquebag container this is a lot like a...

Question details

Write a UniqueBag container. This is a lot like a Bag in that it supports add() and Iteration, except for one important thing: if you try to add a value that’s already in the UniqueBag, the value won’t be added. No error will be thrown, but the add() method will have no effect. So, if we add 1, 3, 2, 1, 4, 2 and 3, the UniqueBag will only contain the values 1, 2, 3 and 4.

Use the code for Bag in the book as your starting point. Be sure to implement the Generic mechanism. Also, here’s a tip: you probably need to compare values in your UniqueBag class, so it won’t work with any possible type of Java Objects – the values must be things that can be compared (so, your class should start out something like public class UniqueBag>). In the main routine of UniqueBag ( public static void main(String[] args) ), you should create a couple of UniqueBag objects for different types of data – maybe one for ints and one for Strings – and test them out.

*** Here is the Bag.java Below ***

import java.util.Iterator;

public class  Bag<Item> implements Iterable<Item> {
    private Node first;  // first node in list
    private  class Node   {
        Item item;
        Node next;
    }
    public void add(Item item)   {  // same as push() in Stack
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
    }
    public Iterator<Item> iterator()   {
        return new ListIterator();
    }
    private class ListIterator implements Iterator<Item>   {
        private Node current = first;
        public boolean hasNext()       {
            return current != null;
        }
        public void remove() { }
        public Item next()       {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }
}
Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution