开发者

Need to find Basic Operations Sets Union/Intersect/Symmetric Difference JAVA

Need to finish implementing this to use UseSet class. Not sure if what I have implemented is 100% correct.

However I need help with the 开发者_如何学JAVAUnion and SysDiff.

public class Set
{
   private ArrayList<Integer> elements;

   public Set()
   {
       elements = null;
   }

   public Set(ArrayList<Integer> s)
   {
       int i;
       elements = new ArrayList<Integer>();
       for(i=0; i<s.size(); i++)
          elements.add(s.get(i));
   }

   public Set(int[] s)
   {
       int i;
       elements = new ArrayList<Integer>();
       for(i=0; i<s.length; i++)
          elements.add(s[i]);
   }

   public String toString()
   {
       //implement this method
   }

   public boolean isElement(int elt)
   {
       int i
    for (i=0; i < elements.size(); i++)
    {
        if (elements.get(i) == elt)
        return true;
    }
    return false

   }

   public int cardinality()
   {
       return elements.size();
   }

   public Set intersect(Set s)
   {
    Array list <interger> iset = new Array(ist<interger>();
    int i;
    for (i=0; i<elements.size(); i++)
    {
        if (s2.isElement (elements.get(i)))
        iSet.add(elements.get(i)));
   }
    return new set(iset)
}

   public Set union(Set s)
   {
       //implement this method
   }

   public Set symDiff(Set s)
   {
       //implement this method
   }


Have you considered using one of the Java-provided classes, such as TreeSet? Most of the basic set operations can be implemented far more easily using such a class as a starting point.

For example:

  • Your isElement() method is named contains() in Set/TreeSet

  • cardinality() is size()

  • intersect can be implemented using retainAll()

  • union() can be implemented using addAll()

  • symDiff() can be implemented using removeAll() to remove the intersection elements from the union of two sets.


Please see the Oracle documentation on performing mathematical set operations with the java Set interface:

http://download.oracle.com/javase/tutorial/collections/interfaces/set.html

You can do unions and intersects with ease.


Java has its basic implementation. For more capabilities, try the Apache Commons library:

Commons-Collections seek to build upon the JDK classes by providing new interfaces, implementations and utilities. There are many features, including...

http://commons.apache.org/collections/

The CollectionUtils class is particularly useful for your task (e.g., addAll:

http://commons.apache.org/collections/api-release/org/apache/commons/collections/CollectionUtils.html#addAll(java.util.Collection,%20java.util.Enumeration).

You can see the implementation and take ideas here:

http://svn.apache.org/viewvc/commons/proper/collections/trunk/src/java/org/apache/commons/collections/CollectionUtils.java?view=markup

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜