sdj89

Java数组转字符串

Java自带toString()方法,确实方便了不少,但是要正确使用。数组直接使用toString()的结果是[类型@哈希值]。这是因为Object类中的toString()如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * Returns a string representation of the object. In general, the
 * <code>toString</code> method returns a string that
 * "textually represents" this object. The result should
 * be a concise but informative representation that is easy for a
 * person to read.
 * It is recommended that all subclasses override this method.
 * <p>
 * The <code>toString</code> method for class <code>Object</code>
 * returns a string consisting of the name of the class of which the
 * object is an instance, the at-sign character `<code>@</code>\', and
 * the unsigned hexadecimal representation of the hash code of the
 * object. In other words, this method returns a string equal to the
 * value of:
 * <blockquote>
 * <pre>
 * getClass().getName() + \'@\' + Integer.toHexString(hashCode())
 * </pre></blockquote>
 *
 * @return  a string representation of the object.
 */
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

而数组类中并没有对此方法重写(override),仅仅是重载(overload)为类的静态方法(参见java.util.Arrays)。

所以数组转为字符串应写成:

1
Arrays.toString(a)

这种方法的toString()是带格式的,也就是说输出的是[a, b, c],而且还带有空格,如果仅仅想输出abc则需用以下两种方法:

方法1:直接在构造String时转换。

1
2
char[] data = {\'a\', \'b\', \'c\'};
String str = new String(data);

方法2:调用String类的方法转换。

1
String.valueOf(char[] ch)

分类:

技术点:

相关文章:

  • 2021-10-08
  • 2021-11-07
  • 2021-12-27
  • 2021-11-07
  • 2021-11-17
  • 2021-11-04
  • 2021-11-07
  • 2021-11-07
猜你喜欢
  • 2021-11-30
  • 2021-11-17
  • 2021-11-19
  • 2021-11-17
  • 2021-11-07
  • 2021-09-05
相关资源
相似解决方案