数组是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入门知识,就请来关注我们的网站吧。
推荐阅读: