Java:做自己的数据类型? (例如,长长双倍?)
我只是想知道是否可以创建自己的数据类型? 因此,如果您需要更高的精度,而其中一种基本类型不支持,您可以“创建”自己的类型来满足您的要求。
这可能吗?如何实现?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看一下
BigDecimal
回答你的问题 - 是的,你可以创建数据类型,但它们不能是原始类型(例如
int
、double
、 ETC)。它们必须是类,就像BigDecimal
(和BigInteger
)的情况一样,以及使用
Big*
类的进一步建议 - 如所写,它们是不可变的。这意味着调用add(..)
不会更改对象 - 它会返回反映更改的新对象。 IETake a look at
BigDecimal
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 withBigDecimal
(andBigInteger
)And a further advice for using the
Big*
classes - as written, they are immutable. This means that callingadd(..)
doesn't change the object - it returns a new object that reflects the change. I.e.如果您要求的话,您无法在 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
(andBigInteger
) should be your starting points for numeric types with more precision.听起来您可能在
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
一切皆有可能。
然而,这并不意味着有人以前没有做过这件事,而且比你以前的效率要高得多。
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.