java数组转为字符串_java数组转字符串要如何转换?一般有几种方法?

数组是java中一个重要的类型,小伙伴们知道如何将数组转为字符串吗?下面就让小编为你介绍一下吧。

在数组中直接用

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

* Returns a string representation of the object. In general, the

toString 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.

* The toString method for class Object

* returns a string consisting of the name of the class of which the

* object is an instance, the at-sign character `@', 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:

 
  

* getClass().getName() + '@' + Integer.toHexString(hashCode())

*

* @return  a string representation of the object.

*/

public String toString()

{

return getClass()

.getName() + "@" + Integer.toHexString(hashCode());

}

在数组类中并没有对此方法重写(override),仅仅是重载(overload)为类的静态方法。

所以数组转为字符串应写成:Arrays.toString(a)

数组转字符串一般而言有三种方法:

一、遍历String[] arr = { "0", "1", "2", "3", "4", "5" };// 遍历

StringBuffer str5 = new StringBuffer();for (String s : arr) {

str5.append(s);

}

System.out.println(str5.toString()); // 012345

二、使用StringUtils的join方法//数组转字符串 org.apache.commons.lang3.StringUtils

String str3 = StringUtils.join(arr); // 数组转字符串,其实使用的也是遍历

System.out.println(str3); // 012345

String str4 = StringUtils.join(arr, ","); // 数组转字符串(逗号分隔)(推荐)

System.out.println(str4); // 0,1,2,3,4,5

三、使用ArrayUtils的toString方法// 数组转字符串 org.apache.commons.lang3.ArrayUtils

String str2 = ArrayUtils.toString(arr, ","); // 数组转字符串(逗号分隔,首尾加大括号)

System.out.println(str2); // {0,1,2,3,4,5}

以上就是关于数组如何转为字符串的所有内容了,数组在java中经常会被使用到,如果你还想了解更多数组相关java入门知识,就请来关注我们的网站吧。

推荐阅读:

  • 6
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值