How to Implement Union Method in Java Interface?

  • Context: Comp Sci 
  • Thread starter Thread starter Robben
  • Start date Start date
  • Tags Tags
    Java
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
5 replies · 2K views
Robben
Messages
166
Reaction score
2

Homework Statement



How do I take the union between an object called on and the object passed in the parameter?

Homework Equations



None

The Attempt at a Solution



I have an interface:

Java:
import java.util.Set;

    /**
     * An extended Set where there is added functionality
     *
     * @version 3/23/14
    */
    public interface NewSet<T> extends Set<T> {
        /**
         * Calculates the set union with the given input
         *
         * @param set - the set to perform the operation along with
         * @return  the set representing the invoked set and the parameter
        */
         NewSet<T> union(NewSet<T> set);

         //and a bunch more methods ...
    }

And I have a class that extends this interface:

Java:
    import java.util.ArrayList;
    public class gSet<T> implements NewSet<T> {
        // ...
    }

Now, the union method requires a NewSet object to be called on. The Union will be performed between the object called on and the object passed in the parameter, which is set. But I am confused on how to do this?
How do I call on a NewSet object in order to take the union between the object called on and the object passed in?

Do I just do:

Java:
    public NewSet<T> union(NewSet<T> set) {
        NewSet<T> calledOn = new ArrayList<T>();
        // ...
    }

Or is that totally wrong and I am not understanding what it means for an object to be called on?
 
on Phys.org
jedishrfu said:
You'd walk the list of your argument NewSet and if not present in the 'this' instance then add it to the 'this' instance.
Hm, what do you mean by walk the list?
 
jedishrfu said:
Use a for loop
Java:
Set myset = new HashSet();
myset.add(obj1);
...

for (Object x : myset) {
    ...
}

http://tutorials.jenkov.com/java-collections/set.html#java-set-example
I can't use Hashset, I can only use ArrayList. But from what I can understand from your code is you created an instance of a Set, which I can't do because Arraylist isn't a set. So do I just create an instance of NewSet, i.e.

Java:
NewSet<T> calledOn = new ArrayList<T>();
 
I am really not understanding this. The changes I made was:

Java:
public class GSet<T> implements NewSet<T> {
    private List<T> list = new ArrayList<>();

    public NewSet<T> union (NewSet<T> set)  {
        NewSet<T> rSet = new GSet<T>();
        // ...
        return rSet;
    }
}

But I am still not understanding how to call on a NewSet object in order to take the union between the object called on and the object passed in?