Java关于数组转化成格式化的字符串输出

int[] arr ={1,2,3,4,5};
System.out.println(arr);//System.out.println(arr.toString());
//都是输出[I@7150bd4d  即[类型@哈希值

String arrString = Arrays.toString(arr);
System.out.println(arrString);
//输出[1, 2, 3, 4, 5]

Java中所有的类,不管是Java库里的类,还是你自己创建的类,都是继承Object这个类的。Object类里面有一个方法toString(),那么所有的类创建的时候都有一个toSting方法。

java输出用的函数print();是不接受对象直接输出的,只接受字符串或者数字之类的输出,所以print(a)中会自动调用a这个对象的toString()方法。那么你想把一个创建好的对象拿来输出怎么办

package com.spring.h3; 
public class Test2 {
    public static void main(String[] args) {
        System.out.println("new Test2()==="+new Test2());
        //输出结果为:new Test2()===com.spring.h3.Test2@18a992f
    }
}
————————————————
此段代码原文链接:https://blog.csdn.net/feicongcong/article/details/77893717

按照print接受的类型来说,s1是不能直接输出的,那么是否代表这个是不能编译运行的呢?当然不是。因为当print检测到输出的是一个对象而不是字符或者数字时,那么它会去调用这个对象类里面的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)。所以,数组直接使用toString()的结果也是[类型@哈希值]。
若想输出成 [a , b, c] 的格式应该用Array.toString方法将数组转化成格式化的字符串。

int[] arr ={1,2,3,4,5};
String arrString = Arrays.toString(arr);
System.out.println(arrString);
//输出[1, 2, 3, 4, 5]

如果仅仅想输出 abc 这种格式,则需用以下两种方法:
方法1:直接在构造String时转换。

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

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

String.valueOf(char[] ch);
发布了59 篇原创文章 · 获赞 111 · 访问量 6241

猜你喜欢

转载自blog.csdn.net/qq_37717494/article/details/104978846
今日推荐