How can an object get its key from a HashMap?

91 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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.