gpt4 book ai didi

Java char[] 中的 toString 方法

转载 作者:行者123 更新时间:2023-12-01 23:18:25 25 4
gpt4 key购买 nike

我以为 toString 方法会将 char 数组转换为 String,但我错了。

    char[] k=new char[2];
k[0]='k';
k[1]='k';
System.out.println(k.toString());

此代码将输出:[C@112f614。

这段代码 k.toString() 到底发生了什么?

我不应该在 char 数组中调用 toString 方法吗?

谢谢!

新年快乐!

最佳答案

您想使用 Arrays.toString(char[]{'a','b'});

<小时/>

你可以使用

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

查看javadoc

public String(char[] value) Allocates a new String so that it represents the sequence of characters currently contained in the character array argument. The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string. Parameters: value - The initial value of the string

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

在数组上调用 toString 将会调用 Object 的 toString 方法。这将返回您的 hashCode

public String 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())
Returns: a string representation of the object.

关于Java char[] 中的 toString 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20873082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com