Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 6 of 6

Thread: Generics help

  1. #1
    New Coder
    Join Date
    Feb 2010
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Generics help

    So I have this assignment where I am acting as a set. A set that holds numbers. In other words an array I am guessing. So he gave us a generic interface. Then we have to use another class and finish those methods. I'm having trouble because I've never used Generics before. My professor created some methods, but I don't know where to start with the others that aren't coded yet. So I guess I need to take what is says in the javadocs of the interface and implement it in the ArraySet class. My Professor gave me both of these. He implemented some methods, but not all. I have to finish the rest in the ArraySet class.

    Here is the generic interface.

    Code:
    import java.util.Iterator;
    
    /**
     * Specifies an abstract data type for a completely unordered collection of
     * generic objects that is not permitted to contain any duplicated elements, as
     * defined by the generic object's equals method.
     * 
     * @author Lewis & Chase ISBN 0-321-24584-9 Ch03
     * @version 2011-09-15 by D.P. Daugherty
     * 
     */
    public interface SetADT<T> {
    
    	/**
    	 * Adds one element to the set, but only if an equal element is not already
    	 * contained therein.
    	 * 
    	 * @param element
    	 *            the element to be added
    	 */
    	public void add(T element);
    
    	/**
    	 * Removes and returns a randomly selected element from the set and adjusts
    	 * the set size accordingly
    	 * 
    	 * @return the element which has been removed from the set
    	 * @throws EmptySetException 
    	 */
    	public T removeRandom() throws EmptySetException;
    
    	/**
    	 * Removes the specified element if it is present in the set, otherwise
    	 * makes no changes
    	 * 
    	 * @param element
    	 */
    	public void remove(T element);
    
    	/**
    	 * Combines the elements of two sets into a third new set with no duplicates
    	 * permitted
    	 * 
    	 * @param set
    	 *            the set to be combined with this set
    	 * @return a new set that contains the union of the two sets being combined
    	 */
    	public SetADT<T> union(SetADT<T> set);
    
    	/**
    	 * Checks to see if an element is already contained in the set
    	 * 
    	 * @param element
    	 *            the element to be checked for containment
    	 * @return true if element is contained in the set, false otherwise
    	 */
    	public boolean contains(T element);
    
    	/**
    	 * Check to see if two sets are exactly equal, ignoring order of the
    	 * elements
    	 * 
    	 * @param set
    	 *            the set to be checked for equality
    	 * @return true if two sets contain exactly the same elements
    	 */
    	public boolean equals(SetADT<T> set);
    
    	/**
    	 * Check to see if set contains no elements
    	 * 
    	 * @return true if set has no elements, false otherwise
    	 */
    	public boolean isEmpty();
    
    	/**
    	 * Returns the number of distinct elements in the set
    	 * 
    	 * @return count of distinct elements
    	 */
    	public int size();
    
    	public Iterator<T> iterator();
    
    	/**
    	 * Returns a list of elements in the set separated by commas and enclosed in
    	 * square brackets
    	 * 
    	 * @return a string describing the contents of the set
    	 */
    	public String toString();
    }
    This is my other class:

    Code:
    import java.util.Iterator;
    import java.util.Random;
    
    
    
    public class ArraySet<T> implements SetADT<T> {
    	
        private static Random generator = new Random();
    	private final int DEFAULT_CAPACITY = 100;
    	private T[] contents;
    	private int count;
    
    	public ArraySet(int initialCapacity) {
    		this.count = 0;
    		this.contents = (T[])(new Object[initialCapacity]);
    	}
    
    	public ArraySet() {
    		this.count = 0;
    		this.contents = (T[])(new Object[DEFAULT_CAPACITY]);
    	}
    
    
    
    	@Override
    	public void add(T element) {
    		if(!this.contains(element)){
    			
    			if(size() == contents.length){
    				expandCapacity();
    			}
    			contents[count]= element;
    			count++;
    		}
    	}
    
    	private void expandCapacity() {
    		T[] larger = (T[])(new Object[contents.length*2]);
    		
    		for(int index=0;index<contents.length;index++){
    			larger[index]=contents[index];
    		}
    		contents=larger;
    	}
    
    	@Override
    	public T removeRandom() throws EmptySetException {
    		if(isEmpty()){
    			throw new EmptySetException();
    		}
    		int index = generator.nextInt(count);
    		T element = contents[index];
    		contents[index]=contents[count-1];
    		contents[count-1]=null;
    		count--;
    		return element;
    		
    	}
    
    	@Override
    	public void remove(T element) {
    		// TODO Auto-generated method stub
    
    	}
    
    	@Override
    	public SetADT<T> union(SetADT<T> set) {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    	@Override
    	public boolean contains(T target) {
    		for(int i=0;i<count;i++){
    			if(contents[i].equals(target)){
    				return true;
    			}
    		}
    		return false;
    	}
    
    	@Override
    	public boolean equals(SetADT<T> set) {
    		// TODO Auto-generated method stub
    		return false;
    	}
    
    	@Override
    	public boolean isEmpty() {
    		if(this.count == 0){
    			return true;
    		}
    		else{
    			return false;
    		}
    		/* More tersely
    		return(count==0);
    		 */
    		/* or
    		 * if(count==0)return true;
    		 * else return false;
    		 */
    	}
    
    	@Override
    	public int size() {
    		// TODO Auto-generated method stub
    		return count;
    	}
    
    	@Override
    	public Iterator<T> iterator() {
    		// TODO Auto-generated method stub
    		return null;
    	}
    
    }

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Since this is an assignment, you will need to be very specific to the problem you are actually having. We cannot just implement these methods.
    Don't think too much into generics. 'T' is simply anything. You may operate on it as if it is an object, but avoid casting it within a generic.

    The only one I will give you is the iterator, since that has no javadoc comments on it, and its not as clear when dealing with a direct array. What you do with this is cast it to a generic List<T> and fetch the iterator off of the collection. Alternatively, you can write your own class that implements Iterator, Iterable, and use that to iterate the collection. To do so in Java, use the Arrays class and fetch the asList:
    PHP Code:
    public Interator<Titerator()
    {
        return 
    Arrays.asList(this.contents).iterator();

    As for the rest, follow the javadoc and the other implemented methods to determine what code to implement.

  • Users who have thanked Fou-Lu for this post:

    BuhRock (09-16-2011)

  • #3
    New Coder
    Join Date
    Feb 2010
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Well the javadocs are in the SetADT interface. So for the remove method, would I do the same thing as the removeRandom method except I wouldn't use the generator object of the Random class?

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Quote Originally Posted by BuhRock View Post
    Well the javadocs are in the SetADT interface. So for the remove method, would I do the same thing as the removeRandom method except I wouldn't use the generator object of the Random class?
    No that won't work. You are given a type T when removing, so what you need to do is use an iteration technique (a for loop is perfect), and if contents[i].equals is true against the argument element, set that offset to null.

  • #5
    New Coder
    Join Date
    Feb 2010
    Posts
    24
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Will this work?

    Code:
    public void remove(T element) {	
    	for(int i = 0; i < count-1; ++i) {
    		if(contents[i].equals(element)) {
                        for(int j = i; j < count-1; ++j)
                            contents[j] = contents[j+1];
                         --count;
                        return;
                    }
    	}
    }

  • #6
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Yes, but you'll need to set the last value of the array to null as well. I'm also not a fan of using a break when you can avoid it (although there is nothing theoretically wrong with it, you may want to see what your instructor thinks of a break in a loop).
    PHP Code:
    public void remove(T element)
    {
        
    boolean bRemoved false;
        for (
    int i 0count && !bRemoved; ++i)
        {
            if (
    contents[i].equals(element))
            {
                for (
    int j icount 1; ++j)
                {
                    
    contents[j] = contents[1];
                }
                
    bRemoved true;
                --
    count;
                
    contents[j] = null;
            }
        }
    }

    // An alternative; this appears that it would work as well (untested)
    public void remove(T element)
    {
        
    T[] elem = (T[])new Object[this.contents.length];
        for (
    int i 0int j 0count 1; ++i)
        {
            if (!
    this.contents[i].equals(element))
            {
                
    // NOT this element
                
    elem[j++] = this.contents[i];
            }
        }
        
    this.contents elem;



  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •