title: toString using generic variables?
body: <p>So there I have this Bag class here, to which I added a <code>remove(T x)</code> method, and now I want to print this, I know I have to use the <code>toString()</code> method but I keep getting either compilation error or still getting the hash code of the object <code>b</code>... there is my interpretation of this but still doesn't work, my solution (the particular) gives me error on the <code>return bag[i]</code> line :(</p>
  
  <pre><code>class Bag&lt;T&gt; {// 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 &amp;&amp; numElements&gt;0){
              for(int i = 0; i &lt; 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&lt;numElements; i++)
                  if (bag[i].equals(x)) // .equals because T a class 
                      count++;
              return count;
      }
  
      public String toString(){
          for(int i = 0; i &lt; numElements; i++){
              return bag[i];
          }
      }
  }
  
  class GenericExample {
      public static void main(String[] args) {        
          Bag&lt;String&gt; b = new Bag&lt;String&gt;();
          b.add("cat"); b.add("dog"); b.add("cat"); 
  
      }
  }
  </code></pre>
  
  <p>I also tried typing <code>String.valueOf(bag[i])</code>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..</p>