Java:做自己的数据类型? (例如,长长双倍?)

发布于 2024-08-24 18:41:23 字数 94 浏览 3 评论 0原文

我只是想知道是否可以创建自己的数据类型? 因此,如果您需要更高的精度,而其中一种基本类型不支持,您可以“创建”自己的类型来满足您的要求。

这可能吗?如何实现?

I'm just pondering about whether or not it's possible to create one's own data type?
So if you need more precision, that's not supported by one of the basic types, you could just "create" your own fullfilling your requierements.

Is that possible and how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

世界如花海般美丽 2024-08-31 18:41:23

看一下 BigDecimal

不可变的、任意精度的有符号十进制数

回答你的问题 - 是的,你可以创建数据类型,但它们不能是原始类型(例如 intdouble、 ETC)。它们必须是类,就像 BigDecimal (和 BigInteger)的情况一样,

以及使用 Big* 类的进一步建议 - 如所写,它们是不可变的。这意味着调用 add(..) 不会更改对象 - 它会返回反映更改的新对象。 IE

BigDecimal dec = BigDecimal.ZERO;
dec.add(new BigDecimal(5)); // nothing happens
dec = dec.add(new BigDecimal(5)); // this works

Take a look at BigDecimal

Immutable, arbitrary-precision signed decimal numbers

And to answer your question - yes, you can crate data types, but they can't be primitive types (like int, double, etc). They have to be classes, just like the case with BigDecimal (and BigInteger)

And a further advice for using the Big* classes - as written, they are immutable. This means that calling add(..) doesn't change the object - it returns a new object that reflects the change. I.e.

BigDecimal dec = BigDecimal.ZERO;
dec.add(new BigDecimal(5)); // nothing happens
dec = dec.add(new BigDecimal(5)); // this works
酒与心事 2024-08-31 18:41:23

如果您要求的话,您无法在 Java 中创建自己的自定义值类型。当然,您可以创建自己的引用类型 - 毕竟,这就是 Java 中的每个类。

但正如其他人所说,BigDecimal(和 BigInteger)应该是更精确的数字类型的起点。

You can't create your own custom value types in Java, if that's what you're asking. You can, of course, create your own reference types - that's what every class in Java is, after all.

But as others have said, BigDecimal (and BigInteger) should be your starting points for numeric types with more precision.

私藏温柔 2024-08-31 18:41:23

听起来您可能在 BigDecimal 类之后:

http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html

Sounds like you might be after the BigDecimal class:

http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html

紫轩蝶泪 2024-08-31 18:41:23

一切皆有可能。

然而,这并不意味着有人以前没有做过这件事,而且比你以前的效率要高得多。

BigInteger 和 BigDecimal 就是您正在寻找的。

Everything is always possible.

That doesn't mean that somebody hasn't already done it before however, and much more efficiently than you ever will.

BigInteger and BigDecimal is what you're looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文