code: static String collectionToString(Collection<?> c) {
          final Object[] a = c.toArray();
          final int size = a.length;
          if (size == 0)
              return "[]";
          int charLength = 0;
  
          // Replace every array element with its string representation
          for (int i = 0; i < size; i++) {
              Object e = a[i];
              // Extreme compatibility with AbstractCollection.toString()
              String s = (e == c) ? "(this Collection)" : objectToString(e);
              a[i] = s;
              charLength += s.length();
          }
  
          return toString(a, size, charLength);
      }
docs: An implementation of Collection.toString() suitable for classes
  with locks.  Instead of holding a lock for the entire duration of
  toString(), or acquiring a lock for each call to Iterator.next(),
  we hold the lock only during the call to toArray() (less
  disruptive to other threads accessing the collection) and follows
  the maxim "Never call foreign code while holding a lock".