I’m having to create a Bag class by using a collection (not Java’s built in Collection). I’m having trouble figuring out the equal() method for this. Basically it needs to check if both bags are the same size, create copies for them, use a union to join them, and in a for loop check whether the current value is in each bag; if so, remove them. If both bags are empty then they are equal. For some reason the code keeps spitting out false?
I apologize for all the code, but it’s hard to pinpoint what to leave out or not, since most of the code coincides.
Thanks for all of the help!!
EDIT: This also goes along with this question: Building a bag class in Java
public class Bag<t> implements Plan<t>{
private final int MAX = 10;
private final int DEFAULT = 6;
private static Random random = new Random();
private t[] content;
private int count;
//Constructors
public Bag(){
count = 0;
content = (t[]) (new Object[DEFAULT]);
}
public Bag(int capacity){
count = 0;
if(capacity<MAX)
content = (t[])(new Object[capacity]);
else System.out.println("Capacity must be less then 10");
}
//Implemented Methods
public void add(t e) {
try{
if(!contains(e) && (!(size() == content.length))){
content[count] = e;
count++;
}
}catch (ArrayIndexOutOfBoundsException exception){
System.out.println("Bag is Full");
}
}
public boolean isEmpty() {
return count==0;
}
public boolean contains(t e) {
Object location = null;
for(int i=0;i<count;i++)
if(content[i].equals(e)) location=i;
return (location!=null);
}
public int size() {
return count;
}
public void addAll(Bag<t> b) {
for (int i=0;i<b.size();i++)
add(b.content[i]);
}
public Bag<t> union(Bag<t> a, Bag<t> b) {
Bag<t> bigBag = new Bag<t>();
for(int i=0; i<a.size();i++)
bigBag.add(a.content[i]);
for(int k=0; k<b.size();k++)
bigBag.add(b.content[k]);
return bigBag;
}
public boolean equals(Bag<t> e) {
Bag<t> bag1 = new Bag<t>();
Bag<t> bag2 = new Bag<t>();
Bag<t> bag3 = new Bag<t>();
t object;
if(size() == e.size()){
bag1.addAll(this);
bag2.addAll(e);
bag3.union(bag1, bag2);
for(int i=0; i<bag3.size();i++){
object = bag3.content[i];
if((bag1.contains(object)) &&(bag2.contains(object))){
bag1.remove(object);
bag2.remove(object);
}
}
}
return (bag1.isEmpty()&&(bag2.isEmpty()));
}
The problem appears to be in your union() method, or with how you’re using it. Its actually returning a new Bag rather than adding bags
bag1andbag2tobag3which is howequals()is expecting it to behave.Do you know about class methods yet? This is what
union()really is. Add thestatickeyword in the signature, like so.Now, let’s fix the definition of the equals method. The
equals()in the sample code has a signature ofBut this should be
So we have to make sure
ois aBagfirst.Fix a couple brace/compiler errors and I think this might work. I can’t test it without the missing
remove()method though.