2009-12-01 4 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); 
} 

}

, 난 사용되는 모든 위치를 불러 오는되는 것을 시도하고있는 무슨, 문제는 내가 질수 있다는 것입니다 :

그래서이 시도 열쇠가 중복되어있다. 그래서 어떤 종류의 데이터 구조를 사용해야합니까? 사전에 감사합니다.

+0

중복 키를 삽입하려는 시도가있을 때 구조가 어떻게 동작하게할까요? 새로운 키/값 쌍을 완전히 무시 하시겠습니까? 또는 이전 값을 새 값으로 바꿉니 까? – dharga

답변

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

당신은() 해시 코드를 구현해야합니다. 자세한 내용은 here을 참조하십시오.

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

당신이 적절 같음/해시 코드를 정의해야합니다은

이제 포인트 사용 설정에 있는지 여부를 테스트 할 수 있습니다

(가) 포함 (이에 대한 링크의 많음이의) 방법과 같은 :

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>>의 관리 형입니다.

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

참고 : 또한 관심의

당신은 끝낼 수있는 그런 당신에게 Multimap<K,V> invertFrom(Multimap<V,K>)

을 제공하는 Multimaps 클래스를 할 수있다? 와우! null 체크 나 다른 말도 안돼.

참고 : 이것은 성능 측면에서 상대적으로 좋지만 다른 요구에 따라 Point 개체를 다른 답변에서 설명한대로 사용할 수 있습니다.

+0

FWIW, 더 명확한 경우에 대비하여 occupiedPositionsMap.containsEntry (x, y)로 표현할 수도 있습니다. –

관련 문제