java Rectangle 和 Rectangle2D 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2214456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rectangle and Rectangle2D Difference
提问by Cheok Yan Cheng
Currently, I use Rectangle and Rectangle2D (Rectangle2D.Double) interchange.
目前,我使用 Rectangle 和 Rectangle2D (Rectangle2D.Double) 互换。
I was wondering what is the consideration I shall take in, while choosing the correct data type? I do not see any obvious difference, except the Rectangle (sub class of Rectangle2D) are having more API functions.
我想知道在选择正确的数据类型时我应该考虑什么?我没有看到任何明显的区别,除了 Rectangle(Rectangle2D 的子类)有更多的 API 函数。
Thanks.
谢谢。
采纳答案by amarillion
Rectangle uses int coordinates. Rectangle2D is an abstract class that doesn't care if you're using int, double or float coordinates.
矩形使用整数坐标。Rectangle2D 是一个抽象类,它不关心您使用的是 int、double 还是 float 坐标。
If you need the greater precision of double and float, you'll have to go with Rectangle2D.
如果您需要更高精度的 double 和 float,则必须使用 Rectangle2D。
Rectangle2D is the base class, so if you're writing code that operates on rectangular shapes in an abstract way, go for Rectangle2D, and assign it like so:
Rectangle2D 是基类,因此如果您正在编写以抽象方式对矩形进行操作的代码,请使用 Rectangle2D,并像这样分配它:
Rectangle2D rect = new Rectangle2D.Double(double, double, double, double);
or
或者
Rectangle2D rect = new Rectangle(int, int, int, int)
If you know you're only going to deal with ints, you can use Rectangle all the way.
如果你知道你只会处理整数,你可以一直使用 Rectangle 。
You might say that Rectangle should be called Rectangle2D.Integer. But that's not quite it either, because e.g. Rectangle is the only one of the three that implements the serializable interface.
您可能会说 Rectangle 应该称为 Rectangle2D.Integer。但这也不完全是这样,因为例如 Rectangle 是实现可序列化接口的三个中唯一的一个。
Like skaffman commented, it's a bit of a legacy issue.
就像 skaffman 评论的那样,这是一个遗留问题。
回答by neoedmund
class Rectangle extends Rectangle2D, this means you can always convert a Rectangle to Rectangle2D, but for the opposite, you could use Rectangle2D.getBounds().
类 Rectangle 扩展了 Rectangle2D,这意味着您始终可以将 Rectangle 转换为 Rectangle2D,但相反,您可以使用 Rectangle2D.getBounds()。

