Reputation: 21
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 Union 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
}
Upvotes: 2
Views: 5821
Reputation: 40391
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:
You can see the implementation and take ideas here:
Upvotes: 0
Reputation: 86353
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:
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.
Upvotes: 9
Reputation: 39055
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.
Upvotes: 1