str() for containers

Donn Cave donn at
Fri Jun 18 17:56:39 CEST 2004

In article <ad052e5c.0406172153.128f765f at>,
 danb_83 at (Dan Bishop) wrote:

> All Java classes include a toString() method (defined in the root
> class java.lang.Object), which returns the string representation of
> that object.  Each of the standard collection classes in java.util
> defines its toString() method to recursively call toString() on its
> elements.
> For example, the program
>    import java.util.*;
>    public class Foo {
>       public static void main(String[] args) {
>          List lst = new ArrayList();
>          lst.add("a");
>          lst.add("b");
>          lst.add("c");
>          System.out.println(lst);
>       }
>    }
> prints "[a, b, c]".

OK, so it's ambiguous - you don't know from the result
whether there are three elements, or two or one - if
one of the elements has its own ", ".

> (Btw, this reminds me of something I like about Python: There are
> literals for variable length arrays, so you don't have to write code
> like that.)
> The difference from Python's approach is that there isn't an
> equivalent to Python's str/repr distinction.  Obviously, when there's
> only one string conversion method, you won't use the wrong one.

It would be fun to apply that reasoning to arithmetic
operators.  Which one does Java support?

> The other difference is that the built-in array types don't have a
> meaningful toString() method, so
>    public class Foo {
>       public static void main(String[] args) {
>          String[] arr = {"a", "b", "c"};
>          System.out.println(arr);
>       }
>    }
> prints "[Ljava.lang.String;@df6ccd" (or something similar).

Ah, I can see how appealing this system would be.
What elegance!

   Donn Cave, donn at

More information about the Python-list mailing list