In java, Implement a SimpleSet class that holds Strings. Use an Array as the Dat
ID: 3586278 • Letter: I
Question
In java,
Implement a SimpleSet class that holds Strings. Use an Array as the Data Structure that holds the data inside the Set. In this case, Sets do not allow duplicates, but are unordered. You need only implement the following methods:
add – Add an element to the set if it does not already exist
remove – If an element exists, remove it from the set and return it. Otherwise, return null
toString – Allow the user to print a Set to see all the contents of the Set
concatenate – Take a set as an argument. Add all the elements from the argument set to the calling set, while not allowing duplicates
Explanation / Answer
Here is the code for you:
class SimpleSet
{
String[] array;
int numOfElements;
int maxSize = 10;
public SimpleSet()
{
array = new String[maxSize];
numOfElements = 0;
}
//add – Add an element to the set if it does not already exist
public void add(String element)
{
if(numOfElements == maxSize)
return;
boolean duplicate = false;
for(int i = 0; i < numOfElements; i++)
if(array[i].equals(element))
duplicate = true;
if(!duplicate)
{
array[numOfElements] = element;
numOfElements++;
}
}
//remove – If an element exists, remove it from the set and return it. Otherwise, return null
public String remove(String element)
{
int index = -1;
for(int i = 0; i < numOfElements; i++)
if(array[i].equals(element))
index = i;
if(index == -1)
return null;
while(index < numOfElements-1)
array[index] = array[index+1];
numOfElements--;
return element;
}
//toString – Allow the user to print a Set to see all the contents of the Set
public String toString()
{
String temp = "[";
for(int i = 0; i < numOfElements-1; i++)
temp += array[i] + ", ";
temp += array[numOfElements-1] + "]";
return temp;
}
//concatenate – Take a set as an argument. Add all the elements from the argument set to the calling set, while not allowing duplicates
public void concatenate(SimpleSet other)
{
for(int i = 0; i < other.numOfElements; i++)
this.add(other.array[i]);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.