Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rectangle and Rectangle2D Difference

Tags:

java

Currently, I use Rectangle and Rectangle2D (Rectangle2D.Double) interchange.

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.

Thanks.

like image 822
Cheok Yan Cheng Avatar asked Feb 06 '10 19:02

Cheok Yan Cheng


2 Answers

Rectangle uses int coordinates. Rectangle2D is an abstract class that doesn't care if you're using int, double or float coordinates.

If you need the greater precision of double and float, you'll have to go with 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 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.

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.

Like skaffman commented, it's a bit of a legacy issue.

like image 80
amarillion Avatar answered Oct 18 '22 11:10

amarillion


class Rectangle extends Rectangle2D, this means you can always convert a Rectangle to Rectangle2D, but for the opposite, you could use Rectangle2D.getBounds().

like image 7
neoedmund Avatar answered Oct 18 '22 12:10

neoedmund