Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-6538167

(coll) Please add Collections.toString(Collection collection, String separator)

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Won't Fix
    • Icon: P5 P5
    • None
    • 6
    • core-libs

      A DESCRIPTION OF THE REQUEST :
        Today there is only one simple way to convert any collection to string representation: AbstractCollection.toString() method. This method uses ", " string to separate elements.

      Unfortunately, it is not often case when a collection (set or list) contains only 3-4 elements and toString() method for these elements returns very short strings. As a result, the string returned by AbstractCollection.toString() is usually long or even very long.

      Converting collections to string is very useful for debugging and logging goals. But it would be very good if there would be a version of toString method allowing to specify the separator inserted between elements. If a collection contains at least several tens or hundreds elements, or if toString() returns detailed result for every element, the line separator looks much better for logging such collection or printing it on the console.

      So, I offer to include the following method into standard java.util.Collections class:
      public static String toString(Collection collection, String separator);
      This method should work as collection.toString(), but should use the given separator instead ", " string. (Such a method cannot be added into Collection or List interface due to compatibility issues.)

      Possible usage example:

      List<Circle> list = ...; // list of 20-30 instances of my Circle class
      logger.fine(String.format("Circles:%n " + Collections.toString(list, String.format("%n ")));

      This code should log the text alike the following:

      Circles:
          x=10, y=10, r=15
          x=20, y=10, r=10
          ...

      The analogous methods may be added into java.util.Arrays class, in addition to already included Arrays.toString(...) methods.


      JUSTIFICATION :
        Programming debugging or logging code often requires to build readable string representation of middle-size collections (tens or hundreds elements), but standard toString() method usually returns very long and unreadable string. It is very often task, and I think the solution could be added into standard java.util.Collections class.


      CUSTOMER SUBMITTED WORKAROUND :
      Almost any my package contains required package-private method :)

            martin Martin Buchholz
            ndcosta Nelson Dcosta (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: