toString()只对调试有用吗? [英] Is toString() only useful for debugging?

查看:152
本文介绍了toString()只对调试有用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了当然,它们与原语一起使用。我看到的大多数(如果不是全部)实现仅从程序员的角度来看是有用的。

Besides of course, their use with primitives. Most (if not all) of the implementations I see are only useful from a programmer viewpoint.

EDIT :我知道我应该覆盖默认行为,这就是为什么我提到实现:)。而且我确实得到了在GUI中需要字符串表示的一些组件中覆盖它的价值。但是,至少在JDK中,我看到很多的实现只在你需要调试对象实例时才会使用。

EDIT: I understand that I'm supposed to override the default behavior, that's why I mentioned implementations :). And I do get the value of overriding it in some components requiring a String representation inside a GUI. However, in the JDK at least, I see lots of implementations that only come to use whenever you need to debug the object instances.

为什么它是否植根于Object类,因为它只对GUI /调试工具有用吗?还有其他用途我不知道吗?

Why is it rooted at the Object class, since that is only seems useful for GUI/debugging stuff? are there other uses I'm not aware of?

推荐答案

toString()在你想要一个对象的字符串表示时很有用。当然,这是出于调试目的,但也可以有效地将操作结果输出给用户。

toString() is useful whenever you want a string representation of an object. Naturally that happens for debugging purposes, but can also be valid to output results of operations to the user.

例如,假设您有一个处理复数的Complex类。如果你想以 3 + 2i 的格式将它们打印给用户,如果它们定义toString()就很方便,因为你不必每次都写入格式,输出就是是一致的。如果您想要更改该表示形式,例如更改为 3 + 2j ,则只需要触摸Complex类中的toString()方法。

For example, let's say you have a Complex class which handles complex numbers. If you want to print them out to an user in a format like 3 + 2i, it is handy if they define toString() as you do not have to write the format every time and the output will be consistent. If you ever want to change that representation, for example to 3 + 2j, you only need to touch the toString() method in the Complex class.

所以toString()也不是为了调试目的,而是获得对象的一致字符串表示的好方法。

So toString() is not for debugging purposes also, but is a good way to get consistent string representations of your objects.

这篇关于toString()只对调试有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆