1. package java.util.concurrent;
    2. import java.util.Collection;
    3. /** 用于 java.util.concurrent 包中*/
    4. class Helpers {
    5. //私有构造函数,不可实例化
    6. private Helpers() {}
    7. /**
    8. * Collection.toString() 的一种实现,适用于有锁的类。
    9. * 代替了以前在整个toString()过程中加锁,或者在每次调用Iterator.next()的时候加锁
    10. * 该方法只在调用toArray()期间加锁,以减少其他线程对访问集合时产生的影响
    11. * 并且遵循在加锁期间,不调用任何外部代码
    12. */
    13. static String collectionToString(Collection<?> c) {
    14. final Object[] a = c.toArray();
    15. final int size = a.length;
    16. if (size == 0)
    17. return "[]";
    18. int charLength = 0;
    19. // Replace every array element with its string representation
    20. for (int i = 0; i < size; i++) {
    21. Object e = a[i];
    22. // Extreme compatibility with AbstractCollection.toString()
    23. String s = (e == c) ? "(this Collection)" : objectToString(e);
    24. a[i] = s;
    25. charLength += s.length();
    26. }
    27. return toString(a, size, charLength);
    28. }
    29. /**
    30. * Like Arrays.toString(), but caller guarantees that size > 0,
    31. * each element with index 0 <= i < size is a non-null String,
    32. * and charLength is the sum of the lengths of the input Strings.
    33. */
    34. static String toString(Object[] a, int size, int charLength) {
    35. // assert a != null;
    36. // assert size > 0;
    37. // Copy each string into a perfectly sized char[]
    38. // Length of [ , , , ] == 2 * size
    39. final char[] chars = new char[charLength + 2 * size];
    40. chars[0] = '[';
    41. int j = 1;
    42. for (int i = 0; i < size; i++) {
    43. if (i > 0) {
    44. chars[j++] = ',';
    45. chars[j++] = ' ';
    46. }
    47. String s = (String) a[i];
    48. int len = s.length();
    49. s.getChars(0, len, chars, j);
    50. j += len;
    51. }
    52. chars[j] = ']';
    53. // assert j == chars.length - 1;
    54. return new String(chars);
    55. }
    56. /** Optimized form of: key + "=" + val */
    57. static String mapEntryToString(Object key, Object val) {
    58. final String k, v;
    59. final int klen, vlen;
    60. final char[] chars =
    61. new char[(klen = (k = objectToString(key)).length()) +
    62. (vlen = (v = objectToString(val)).length()) + 1];
    63. k.getChars(0, klen, chars, 0);
    64. chars[klen] = '=';
    65. v.getChars(0, vlen, chars, klen + 1);
    66. return new String(chars);
    67. }
    68. private static String objectToString(Object x) {
    69. // Extreme compatibility with StringBuilder.append(null)
    70. String s;
    71. return (x == null || (s = x.toString()) == null) ? "null" : s;
    72. }
    73. }

    瓦雀