Java 我需要什么样的数据结构来实现用于存储坐标的哈希表?

Java 我需要什么样的数据结构来实现用于存储坐标的哈希表?,java,data-structures,Java,Data Structures,我需要建立一个职位经理类来告诉我是否有职位 所以我试了一下: enter code here 公共类职位经理{ Hashtable currentPositions = new Hashtable(); void occupiedPosition(int x,int y){ this.currentPositions.put(new Integer("4"),new Integer("5")); this.currentPositions.put(new Integer

我需要建立一个职位经理类来告诉我是否有职位

所以我试了一下:

enter code here

公共类职位经理{

Hashtable currentPositions = new Hashtable();


void occupiedPosition(int x,int y){

    this.currentPositions.put(new Integer("4"),new Integer("5"));
    this.currentPositions.put(new Integer("1"),new Integer("5"));
    this.currentPositions.put(new Integer("11"),new Integer("3"));
    this.currentPositions.put(new Integer("42"),new Integer("55"));
    this.currentPositions.put(new Integer("11"),new Integer("53"));

    Set keys = this.currentPositions.keySet();         // The set of keys in the map.
      Iterator keyIter = keys.iterator();
      System.out.println("The map contains the following associations:");
      while (keyIter.hasNext()) {
         Object key = keyIter.next();  // Get the next key.
         Object value = this.currentPositions.get(key);  // Get the value for that key.
         System.out.println( "   (" + key + "," + value + ")" );
      }

}




 public static void main(String[] args) {
    new PositionManager().occupiedPosition(3, 3);
}
}

当然,这只是一个测试,我试图做的是检索所有使用的位置,问题是我不能有重复的钥匙。 那么我应该使用什么样的数据结构呢。
提前感谢。

我会通过创建一组职位来解决这个问题。集合为只能出现一次的对象集合建模。相比之下,映射结构存储一组键/值关联。从我对你问题的理解来看,我认为一套结构最有意义

// You might just be able to use an existing Point depending on what you
// want to do with the position
class Position {
  int x;
  int y;

  // implementations of hashCode() + equals()
  }
}
您需要实现hashCode(),以便项可以在集合中均匀分布,并实现equals(),以便可以比较对象。有关更多信息,请参阅

Set<Position> positions = new HashSet<Position>();
positions.add(new Position(3,4));
positions.add(new Position(5,6)); // and so on
我建议使用。这实际上是
Map
的托管类型

还有一个有趣的类,它提供了
Multimap invertFrom(Multimap)

然后你可以得到:

public boolean isPositionOccupied(int x, int y) {
    return occupiedPositionsMap.get(x).contains(y);
}
看到了吗?哇!不需要空检查或其他废话


注意:从性能角度来看,这是相对最优的,但根据您的其他需要,您可能希望使用其他答案中提到的
对象。

当尝试插入重复密钥时,您希望结构如何运行?是否希望它完全忽略新的键/值对?或者将旧值替换为新值?FWIW,该值也可以表示为occupiedPositionsMap.containsEntry(x,y),以防您发现更清楚。
public boolean isPositionOccupied(int x, int y) {
    return occupiedPositionsMap.get(x).contains(y);
}