【问题标题】:Store and get data based on their ids根据他们的 id 存储和获取数据
【发布时间】:2014-12-28 06:26:13
【问题描述】:

我正在尝试存储数据并根据他们的 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
Options.add("handpump");
Options.add("Well");

Q_ID=1
Type_question=1
Options.add("random");
Options.add("answer");

有没有办法可以存储它们,以便当我输入 Q_ID = 0 和 Type_Question=1;它只返回手动泵和井,如果输入 Q_ID = 1 和 Type_question=1,它只返回随机和答案。 这可能太明显了,但我什么都想不出来。有什么想法吗?

【问题讨论】:

  • 不同的数据结构适用于不同的事物。为了高效查找,您需要一个“字典”数据结构。 Java 中一个优秀的候选者是Map,例如“HashMap”。
  • 非常感谢我已经解决的建议:)

标签: java arraylist store


【解决方案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 将返回一个包含"handpump""well"ArrayList

您必须确保 Q_ID 始终位于 Type_Question 之前,因为重新排列它们不会返回正确的结果。

【讨论】:

  • 表达式的类型必须是数组类型,但它解析为 HashMap> 它给出了这个错误..有什么想法吗?
  • @zeeshandar 现在尝试编译它 - 我有一些问题。
  • yoursHashMap.put("1,1", randomAnswer);而不是 yourHashMap["1,1"] = randomAnswer;感谢它现在的工作......干杯
猜你喜欢
  • 2013-01-21
  • 1970-01-01
  • 2019-06-23
  • 1970-01-01
  • 2018-04-13
  • 1970-01-01
  • 2013-03-05
  • 2019-11-22
  • 1970-01-01
相关资源
最近更新 更多