Awt's Dimension class can do a lot of things, converting between different numeric types and etc. I'm using these classes to represent cells on big 2d worlds that need to be updated per ms. Can I get a performance hit, if I stick with the Dimension class all along instead of using my custom Pair class? This is my custom Pair class:
public class Pair<A, B> {
private A first;
private B second;
public Pair(A first, B second) {
super();
this.first = first;
this.second = second;
}
public static <A, B> Pair <A, B> createPair(A first, B second) {
return new Pair<A, B>(first, second);
}
@Override
public int hashCode() {
int hashFirst = first != null ? first.hashCode() : 0;
int hashSecond = second != null ? second.hashCode() : 0;
return (hashFirst + hashSecond) * hashSecond + hashFirst;
}
@Override
public boolean equals(Object other) {
if (other instanceof Pair) {
Pair otherPair = (Pair) other;
return
(( this.first == otherPair.first ||
( this.first != null && otherPair.first != null &&
this.first.equals(otherPair.first))) &&
( this.second == otherPair.second ||
( this.second != null && otherPair.second != null &&
this.second.equals(otherPair.second))) );
}
return false;
}
@Override
public String toString()
{
return "(" + first + ", " + second + ")";
}
public A getX() {
return first;
}
public B getY() {
return second;
}
}
When I was looking for Pair implementations I haven't seen the mention of Dimension anywhere, wonder why..
When I was looking for Pair implementations I haven't seen the mention of Dimension anywhere, wonder why..
Well, a Dimension
could be seen as a Pair
but not the other way round. A dimension has two int values while a generic pair can have any combination of types.
Btw a generic pair doesn't provide much more info on the data than that there are two objects in some relation. That's why generally using specialized classes is preferred over pairs, e.g. Dimension
defines the two values as width and height and nothing else, so you gain additional information over just using Pair<Integer, Integer>
.
Besides that, you'd need to note that Dimension
has integer fields and thus can only represent integer extents, i.e. width = 2.5 is not possible. Besides that I'd not use Dimension
for representing positions since although the data seems similar the semantics (meaning) of that data is not (dimension defines an area while positions are points).
You might consider using Point2D.Float
or Point2D.Double
instead.