So there I have this Bag class here, to which I added a remove(T x) method, and now I want to print this, I know I have to use the toString() method but I keep getting either compilation error or still getting the hash code of the object b... there is my interpretation of this but still doesn't work, my solution (the particular) gives me error on the return bag[i] line :(
class Bag<T> {// generic class with T standing for a class
private T[] bag =(T[])(new Object[100]);
private int numElements = 0; // junk in bag[numElements..]
void add(T x) { // put x in bag
bag[numElements] = x; numElements++;
}
void remove (T x){
if(x!=null && numElements>0){
for(int i = 0; i < numElements; i++){
if(bag[i]==x){
bag[i]=bag[numElements];
numElements-=1;
}
}
}
}
int freq(T x) { // how many x’s in bag?
int count = 0;
for (int i=0; i<numElements; i++)
if (bag[i].equals(x)) // .equals because T a class
count++;
return count;
}
public String toString(){
for(int i = 0; i < numElements; i++){
return bag[i];
}
}
}
class GenericExample {
public static void main(String[] args) {
Bag<String> b = new Bag<String>();
b.add("cat"); b.add("dog"); b.add("cat");
}
}
I also tried typing String.valueOf(bag[i])but still had compilation error... Why is there a problem anyway? In this example the T is a String so I can't understand why it's doing that..
You want to change the toString method maybe in the following:
public String toString(){
return Arrays.toString(bag);
}
OR the home brew version
public String toString(){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < numElements; i++){
sb.append(bag[i]);
}
return sb.toString();
}
If the object you put into your bag does not override toString, then you get a string of hashcodes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With