返回对象时的困惑

时间:2018-05-09 20:32:57

标签: java string object tostring

public class MyString {
//instance variables
char[] charArray;
public MyString(char[] chars) {
    charArray = new char[chars.length];
    for (int i = 0; i < chars.length; i++) {
        charArray[i] = chars[i];
    }
}

public MyString print() {
    for (int i = 0; i < charArray.length; i++) {
        System.out.print(charArray[i]);
    }
    return new MyString(charArray);
}
class MyStringClient {

public static void main(String[] args) {
    MyString str1 = new MyString(new char[] {'h', 'a', 'p', 'p', 'y'});
    str1.print();

}

}

您好,我对代码的工作原理有疑问。在我的书中,它希望我自己实现字符串类。我创建了一个名为myString的类和一个名为MyStringClient的类来测试它。代码没有问题,它在执行时输出“happy”但是如果有意义的话,我只是通过试验来实现它。当我回去试图理解我做得更好的时候,我对我的打印功能在MyString类中的工作原理感到困惑。我的书告诉我要创建MyString类型的方法,所以我返回了一个MyString对象,但是如果我为任何普通对象创建一个引用变量并尝试System.out.print(obj ref var),我会得到一些哈希码值。这个函数怎么能显示对象的实际内容,我很困惑。谢谢。

1 个答案:

答案 0 :(得分:0)

Your public class MyString contains a public function print which returns a MyString type.

By creating a str1 MyString variable
MyString str1 = new MyString(new char[] {'h', 'a', 'p', 'p', 'y'});
MyString now contains a char[] called charArray.

Lastly you're calling the print function on that same MyString object.

That print function on your str1 MyString object:
for (int i = 0; i < charArray.length; i++) {
        System.out.print(charArray[i]);
    }

simply prints out each entry in the charArray you populated above with:
new char[] {'h', 'a', 'p', 'p', 'y'}