Java数组转字符串

本文章转载自 http://www.hqhome.net/java/303.html

感谢原作者。


数组直接用 toString()方法返回的并非常常并非我们想要的字符串,而是[类型@哈希值],其原因在于Object类中的toString方法如下所示:

/**
 * 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)。

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

Arrays.toString(a)

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

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

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

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

String.valueOf(char[] ch)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值