博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 数组和字符串的转换--不能通过toString方法
阅读量:4146 次
发布时间:2019-05-25

本文共 3485 字,大约阅读时间需要 11 分钟。

java数组->字符串

       java中所有的类,不管是java库里面的类,或者是你自己创建的类,全部是从object这个类继承的。object里有一个方法就是toString(),那么所有的类创建的时候,都有一个toString的方法。这个方法是干什么的呢?

首先我们得了解,java输出用的函数print();是不接受对象直接输出的,只接受字符串或者数字之类的输出。

Object类中的toString()方法的源代码如下:

/**     * Returns a string representation of the object. In general, the     * {@code 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 {@code toString} method for class {@code Object} * returns a string consisting of the name of the class of which the * object is an instance, the at-sign character `{@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: *

*
     * getClass().getName() + '@' + Integer.toHexString(hashCode())     * 
* * @return a string representation of the object. */ public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
char[] data = {'a', 'b', 'c'};System.out.println(data.toString());  //输出结果为[C@79fc7299
输出会去调用object类里面的toString 方法,根据源码可知,输出结果为[类型@哈希值]。

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

所以,数组直接使用toString(),会去调用object类里面的toString方法,结果是[类型@哈希值]。

数组转字符串可以使用Arrays类中的toString方法Arrays.toString(data)。附上Arrays类的toString方法源码。但是由源码可知,这种方法的toString()是带格式的,也就是说输出的是[a, b, c]。

/**     * Returns a string representation of the contents of the specified array.     * The string representation consists of a list of the array's elements,     * enclosed in square brackets ("[]").  Adjacent elements are     * separated by the characters ", " (a comma followed by a     * space).  Elements are converted to strings as by     * String.valueOf(char).  Returns "null" if a     * is null.     *     * @param a the array whose string representation to return     * @return a string representation of a     * @since 1.5     */    public static String toString(char[] a) {        if (a == null)            return "null";        int iMax = a.length - 1;        if (iMax == -1)            return "[]";        StringBuilder b = new StringBuilder();        b.append('[');        for (int i = 0; ; i++) {            b.append(a[i]);            if (i == iMax)                return b.append(']').toString();            b.append(", ");        }    }
如果仅仅想输出abc则需用以下两种方法:

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

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

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

String.valueOf(data)
String类valueOf方法的源码如下,由源码可知,valueOf实际也是new String对象,和方法1一样

/**     * Returns the string representation of the char array     * argument. The contents of the character array are copied; subsequent     * modification of the character array does not affect the newly     * created string.     *     * @param   data   a char array.     * @return  a newly allocated string representing the same sequence of     *          characters contained in the character array argument.     */    public static String valueOf(char data[]) {        return new String(data);    }

java字符串->数组

如果是 “字符串数组” 转 “字符串”,只能通过循环,没有其它方法     String str = "123abc";    char[] arr = str.toCharArray();  //char数组    for(int i =0;i
 
参考 http://www.cnblogs.com/ningvsban/p/3955483.html 考 http://www.cnblogs.com/ningvsban/p/3955483.html
 
 
你可能感兴趣的文章
Android自动关机代码
查看>>
Android中启动其他Activity并返回结果
查看>>
2009年33所高校被暂停或被限制招生
查看>>
GlassFish 部署及应用入门
查看>>
X-code7 beta error: warning: Is a directory
查看>>
Error: An App ID with identifier "*****" is not avaliable. Please enter a different string.
查看>>
3.5 YOLO9000: Better,Faster,Stronger(YOLO9000:更好,更快,更强)
查看>>
iOS菜鸟学习--如何避免两个按钮同时响应
查看>>
iOS菜鸟学习—— NSSortDescriptor的使用
查看>>
C语言8
查看>>
Qt实现简单延时
查看>>
qml有关矩形说明
查看>>
在qt中使用QSplitter设置初始比例setStretchFactor失效的解决方法
查看>>
repeater的使用
查看>>
qt msvc编译中文乱码解决
查看>>
qt实现点击出现窗口,点击其他任何地方窗口消失
查看>>
QML DropArea拖拉文件事件
查看>>
CORBA links
查看>>
读后感:>
查看>>
ideas about sharing software
查看>>