2014-10-31 59 views
0

我想存儲數據,並把它找回來基於他們ids.The數據類型是數據。存儲和獲取基於其ID

int Q_ID -------> Id of the Question 
int Type_Question ----> Which type is the Question 
ArrayList<String> Options ----> The options are multiple and are determined at run   based on users selection of the options 

現在我想存儲數據。例如以這種方式。有沒有一種方法可以存儲它們,以便當我輸入Q_ID = 0和Type_Question = 1時;它只返回手泵,如果輸入Q_ID = 1和Type_question = 1,它只返回隨機答案。 這可能太明顯了,但我想不出任何事情。任何想法?

+0

不同的數據結構適用於不同的事情。爲了高效查找,您需要一個「字典」數據結構。 Java中的優秀候選人是[Map](http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html),例如「HashMap <>」。 – FoggyDay 2014-10-31 21:05:33

+0

非常感謝我已經解決了它的建議:) – 2014-10-31 21:37:41

回答

1

簡單,稍微哈克你可以做到這一點沒有定義自己的類型的方法是將這些保存在一個HashMap,用繩子結合Q_ID和Type_Question作爲一個連接字符串,像這樣:

HashMap<String, ArrayList<String>> yourHashMap = new HashMap<String, ArrayList<String>>(); 

ArrayList<String> handPumpWell = new ArrayList<String>(); 
handPumpWell.add("handpump"); 
handPumpWell.add("well"); 
yourHashMap.put("0,1", handPumpWell); 

ArrayList<String> randomAnswer = new ArrayList<String>(); 
randomAnswer.add("random"); 
randomAnswer.add("answer"); 
yourHashMap.put("1,1", randomAnswer); 

然後你可以參考的選項列表中任何給定的ID /類型組合,像這樣:

yourHashMap[Q_ID + "," + Type_Question] 

這爲Q_ID = 0Type_Question = 1會返回一個包含一和"well"

但是,您必須確保Q_ID始終位於Type_Question之前,因爲重新排列它們將不會返回正確的結果。

+0

這就是我正在尋找的..謝謝男人:) – 2014-10-31 20:49:01

+0

表達式的類型必須是數組類型,但它解析爲HashMap >它給出這個錯誤..任何想法? – 2014-10-31 20:57:57

+0

@zeeshandar嘗試編譯它 - 我有一些錯誤的東西。 – furkle 2014-10-31 21:05:15