1

Suppose I have a chessboard defined with a HashMap

HashMap <Position,Field> chessboard = new HashMap <Position,Field>();

I declare the Position as

class Position{
  int x;
  int y;
}

When I am trying to make a class for Field object I encounter a problem: the Field should contain a Position because it is defined by it. Ex.

class Field {
  Position pos;
  int color;
  void draw(){
    // draw Field using pos
  }
}

But the Position object is going to be used for HashMap. How could I avoid this redundancy?

Ivan
  • 29
  • 8
  • 1
    just remove it from `Field`. you can access it from `Map` – Braj Jun 02 '14 at 20:08
  • 1
    You can use the same `Position` object for your `Field` object and for the key in the `HashMap`. – rgettman Jun 02 '14 at 20:08
  • Also, your HashMap won't work as expected unless you override `equals` and `hashCode` on `Position`. – user253751 Jun 02 '14 at 20:10
  • When an object's key is part of that object's value, you shouldn't use a map, you should use a *set*. – David Schwartz Jun 02 '14 at 20:11
  • @DavidSchwartz It's easy to access using `Map` when needed based on `Position` – Braj Jun 02 '14 at 20:12
  • 1
    @DavidSchwartz: why? It's quite useful, and a common scenario, to be able to quickly get books by their ISBN, or users by their ID, or whatever. The whole idea of a cache is based on this principle. – JB Nizet Jun 02 '14 at 20:12
  • @JBNizet A *set* has that same property, it just makes the key and the value the same object, which makes it appropriate when the key is logically part of the value. – David Schwartz Jun 04 '14 at 20:13

1 Answers1

2

The cost isn't actually what you think: you're only holding a single reference (four bytes on most systems) to the same Position object in memory. The overhead is minimal; don't even worry about it.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413