str() for containers
Donn Cave
donn at u.washington.edu
Fri Jun 18 11:56:39 EDT 2004
In article <ad052e5c.0406172153.128f765f at posting.google.com>,
danb_83 at yahoo.com (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 u.washington.edu
More information about the Python-list
mailing list