views:

48

answers:

2

I have a varargs contructor like this :

public class Sentence {

   public String[] str;

      public Sentence(Object... text){

        StringBuilder sb = new StringBuilder();
        for (Object o : text) {
          sb.append(o.toString())
          .append(" ");
        }
        System.out.println(sb.toString());

     }

 }

Contructor can get various types of data (ints, strings, and Sentence objects as well). How to do a proper toString method for such class ?

+2  A: 

Not sure exactly what you're trying to achieve, but as the toString() method...

Returns a string representation of the object

...I guess I would store the result of your sb.toString() call as a member String variable (say private String asString), and return that in a toString() method overriding the method in Object:

public String toString() {
  return this.asString;
}
Brabster
it is continuation of this post : http://stackoverflow.com/questions/2373419/one-constructor-multiple-arguments
owca
A: 

You can't print Sentence in toString because you can get infinite loop if you initialize 2 Senence objects by each other.

So, print all strings and objects and if it's possible some data from Sentence object, or only "1 sentence object" to point that it's also passed as an init param.

Roman
Sorry, how do you get an infinite loop?
Simon Nickerson
At the moment he won't get it, but if he add `setText(Object...text)` method or something similar then he can expect for the surprise.
Roman
I think @Roman is assuming that `Sentence` would contain a member variable `Object[] objects` that would keep track of which `Object`s are in the `Sentence`, and that `Sentence` would have some sort of `append()` method of its own to allow adding additional `Object`s. In that case, generating a `String` representation inside `toString()` could cause an infinite loop: `Sentence s1 = new Sentence(); Sentence s2 = new Sentence(s1); s1.append(s2);` That would cause an infinite loop. Those assumptions might not be valid though, and I think @Brabster's solution makes more sense overall.
William Brendel