2009-12-01 26 views
2

我需要建立一個職位經理職位來告訴我職位是否可用。我需要什麼樣的數據結構來實現存儲座標的哈希列表?

所以我想這:

enter code here 

public class PositionManager {

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); 
} 

}

當然這只是一個測試,我所試圖做的是retreiving所使用的所有位置,問題是,我不能有重複的密鑰。 那麼我應該使用什麼樣的數據結構。 在此先感謝。

+0

當你試圖插入一個重複密鑰完成時,你希望結構行爲如何?你希望它完全忽略新的鍵/值對嗎?或用新的價值取代舊價值? – dharga 2009-12-01 21:22:08

回答

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(),以便項目可以在set和equals()中均勻分佈,以便可以比較對象。有關更多信息,請參閱here

Set<Position> positions = new HashSet<Position>(); 
positions.add(new Position(3,4)); 
positions.add(new Position(5,6)); // and so on 

確保你正確定義equals /的hashCode(有大量的這種鏈接)

您現在可以測試一個點是否在使用集中包含的方法,如:

positions.contains(new Point(2,1)); // returns false 
positions.contains(new Point(3,4)); // returns true 
0

我建議使用google-collection's MultiMap。這實際上是Map<K, Collection<V>>的受管理類型。

也感興趣的可能是Multimaps類,它給你Multimap<K,V> invertFrom(Multimap<V,K>)

然後,你可以結了:

public boolean isPositionOccupied(int x, int y) { 
    return occupiedPositionsMap.get(x).contains(y); 
} 

看到了嗎?哇!不需要空值檢查或其他廢話。

注意:從性能的角度來看,這是相對最佳的,但根據您的其他需求,您可能需要使用Point對象,如其他答案中所述。

+0

FWIW,如果你找到更清楚的,也可以表示爲occupiedPositionsMap.containsEntry(x,y)。 – 2009-12-01 21:35:59

相關問題