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 namedcontains()
in Set/TreeSetcardinality()
issize()
intersect
can be implemented usingretainAll()
union()
can be implemented usingaddAll()
symDiff()
can be implemented usingremoveAll()
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
精彩评论