2012-11-25 2 views
0

언제 입력 특정 데이터 항목 (여기에 문자), 내가 좋아하는 관련 요소에 액세스 할 수 있습니다할 수있는 데이터 구조가 않습니다 :

내가 입력 'A'는, 그것이 나에게 액세스를 제공하는 경우를 값 (2, 3, 4, 5), 예를 :

A - 2,3,4,5 
B - 6,7,9 
C - 10, 11, 12, 13 
D - 1,8 
and so on... 

또한 그 ABCD는 데이터 항목, int 또는 문자열이 될 수 있습니다.

선형 배열을 유지 한 다음 배열의 각 항목을 링크 된 목록의 머리글이라고 생각합니다. 위의 데이터 구조에 대한 정확하고 최적의 솔루션입니까? 이 작업을 수행하기위한 데이터 구조가 이미 갖추어져 있습니까?

+2

질문 언어 별인가? 그렇다면 정확합니다. –

+0

주문을 유지해야합니까? – tjameson

+0

@Julien Bourdon - C++, Java –

답변

1

가장 좋은 방법은 테이블 값의 배열 (또는 목록)으로 Hash Table을 사용하는 것입니다. 여기

의 HashMap

Map<String,Integer[]> theMap; 
theMap = new HashMap<String,Integer[]>(); 
theMap.put("A",{2,3,4,5}); 
theMap.put("B",{6,7,9}); 
theMap.put("C",{10,11,12,13}); 
theMap.put("D",{1,8}); 

/* Access Values */ 
int two = theMap.get("A")[0]; 

를 사용하여 자바의 예를 들어 당신은 또한 대신 정수의 배열의 ArrayList를 사용할 수 있습니다. 다음과 같이

코드가 될 것이다 :

ArrayList<Integer> listA = new ArrayList<Integer>(); 
    listA.add(2); 
    listA.add(3); 
    listA.add(4); 
    listA.add(4); 

ArrayList<Integer> listB = new ArrayList<String>(); 
    listB.add(6); 
    listB.add(7); 
    listB.add(9); 

ArrayList<Integer> listC = new ArrayList<Integer>(); 
    listC.add(10); 
    listC.add(11); 
    listC.add(12); 
    listC.add(13); 

ArrayList<Integer> listD = new ArrayList<Integer>(); 
    listD.add(1); 
    listD.add(18); 

    Map<String,List<Integer>> theMap; 
    theMap = new HashMap<String,List<Integer>>(); 
    theMap.put("A",listA); 
    theMap.put("B",listB); 
    theMap.put("C",listC); 
    theMap.put("D",listD); 

    /* Access Values */ 
    int two = theMap.get("A").get(0); 
+0

감사합니다. Julien Bourdon,이게 정말 도움이됩니다. –

+0

다음 줄에 "not a statement"라는 오류가 표시됩니다. theMap.put ("A", {2,3,4,5}); 및 이와 유사한 줄 .. 다음을 시도 : 정수 [] numbers = {2,3,4,5}; String key = "A"; theMap.put (key, numbers); 그리고 잘됩니다. 이 두 코드의 차이점은 무엇입니까? Jdk1.7을 사용하고 있습니다. –

+0

코드를 테스트하지는 않았지만 실제 메서드에서 배열을 직접 지정할 수 없습니다. 어쨌든, OO 철학에 더 쉽게 접근하고 작업하기가 쉽기 때문에 배열 대신 목록을 사용하는 것이 좋습니다. –

0

요소가 목록 (또는 세트) 인 간단한 dictionary/map/associative array을 사용하십시오. 파이썬에서, collections.defaultdict 여기에 도움이 될 수 있습니다

import collections 
d = collections.defaultdict(list) 
A,B,C,D = ['A', 8, 3.0, (1,2)] 
d[A].extend([2, 3, 4]) 
d[A].append(5) 
# d[A] is now [2,3,4,5] 
+0

phihag - 감사합니다. –

관련 문제