Question: Java Box and BoxR Classes- equals Method Add an equals method to both the Box and BoxG classes. Two boxes are the same if they
Java
Box and BoxR Classes- equals Method
Add an equals method to both the Box and BoxG classes. Two boxes are the same if they have the same thing and count. Post only the new methods (do not post the rest of the class that was unchanged).
Box class
public class Box> implements Comparable> {
private T thing;
private int thingCount;
private T[] oldThings;
public Box(T firstThing) {
this.thing = firstThing;
this.thingCount = 1;
//oldThings = new T[5]; // not allowed
oldThings = (T[]) (new Comparable[5]); // allowed
}
public T getContents() {
return thing;
}
public int getCount() {
return thingCount;
}
public void replaceContents(T newThing) {
this.thing = newThing;
thingCount++;
}
@Override
public String toString() {
return thing.toString() + " (item " + thingCount + ")";
}
@Override
public boolean equals(Object other) {
if(other instanceof Box) {
Box otherBox = (Box) other;
boolean sameThing = this.thing.equals(otherBox.thing);
boolean sameCount = this.thingCount==otherBox.thingCount;
return sameThing && sameCount;
} else {
return false;
}
}
@Override
public int compareTo(Box otherBox) {
if(this.thing.compareTo(otherBox.thing)==0) {
return Integer.compare(this.thingCount, otherBox.thingCount);
} else {
return this.thing.compareTo(otherBox.thing);
}
}
}
BoxR class
public class BoxR {
private Object thing;
private int thingCount;
public BoxR(Object firstThing) {
this.thing = firstThing;
this.thingCount = 1;
}
public Object getContents() {
return thing;
}
public int getCount() {
return thingCount;
}
public void replaceContents(Object newThing) {
this.thing = newThing;
thingCount++;
}
@Override
public String toString() {
return thing.toString() + " (item " + thingCount + ")";
}
@Override
public boolean equals(Object other) {
if(other instanceof BoxR) {
BoxR otherBoxR = (BoxR) other;
boolean sameThing = this.thing.equals(otherBoxR.thing);
boolean sameCount = this.thingCount==otherBoxR.thingCount;
return sameThing && sameCount;
} else {
return false;
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
