[英]How do I refer to specific array list
我有一個包含兩個數組的Arraylist。 根據不同類的內容,我想使用數組1或2的信息。但是,我無法弄清楚如何在getQuestions方法中間接引用特定的數組。 我可以在此類中以String格式接收正確的變量mQuestions1
或mQuestions2
,並將其稱為mVersion
。
我的代碼:
public class QuestionLab {
ArrayList<Question> mQuestions1, mQuestions2;
private static QuestionLab sQuestionLab;
private Context mAppContext;
private QuestionLab(Context appContext) {
mAppContext = appContext;
mQuestions1 = new ArrayList<Question>();
mQuestions1.add(new Question(1, R.drawable.a, state));
mQuestions1.add(new Question(2, R.drawable.b, state));
mQuestions1.add(new Question(3, R.drawable.c, state));
mQuestions2 = new ArrayList<Question>();
mQuestions2.add(new Question(1, R.drawable.a, state));
mQuestions2.add(new Question(2, R.drawable.b, state));
mQuestions2.add(new Question(3, R.drawable.c, state));
}
public static QuestionLab get(Context c) {
if (sQuestionLab == null) {sQuestionLab = new QuestionLab(c.getApplicationContext());}
return sQuestionLab;
}
public Question getQuestion(int nr) {
for (Question c : mQuestions) {if (c.getNr() == (nr)) return c;} return null;
}
public ArrayList<Question> getQuestions(){return mQuestions1}
編寫mQuestions1
確實可以,但是不允許我在1和2之間進行更改,因此我需要Arraylist(mVersion)
類的東西
提前致謝!
這很容易。
構建一個HashMap或另一個擁有幾個孩子的基本類。
您是否要隨機選擇哪個問題? 為什么不創建一個被稱為的helperClass(例如Question)
哪個保留一個數組(列表)?
class Question {
Arraylist<String> questions;
//;getter and setter
}
public ArrayList<Question> getQuestions(){
for (Question c : mQuestions) {
ArrayList<String> dummyArray = c.getQuestions();
if (c.size() > 0) {
//randomize it, get it out, whateer.
}
}
}
但是請回到您的問題(以及解決方案,這不是一個很好的方法)。
public ArrayList>Questions> getQuestions() {
if (question_array_1 != null && question_array_2 != null) {
int qCnt = (questions_array_1.size() > question_array_2.size()) ? question_array_1.size() : question_array_2.size();
for (int i = 0; <= qCnt; i++) {
String myQuestion = (Math.random(0,1) == 1) ? question_array_2.getQuestion() : question_array_1.getQuestion();
//or merge it to another arraylist...
}
}
}
另一種技術是將其直接存儲到SQLITEDatabase中(我很喜歡!)。
最后但並非最不重要的一點(在您的情況下可能不是一種很好的技術)是將所有內容與
ArrayList<Question> array_list_all = new ArrayList<Question>();
array_list_all.addAll(first_question_array);
array_list_all.addAll(second_question_array);
然后,您可以foreach它並獲取觸發您的級別或questionID的問題。
...
public static final int USE_FIRST = 0;
public static final int USE_SECOND = 1;
...
public Question getQuestion(final int mode, final int nr) {
ArrayList<Question> listToUse = null;
if (mode == USE_FIRST) {
listToUse = mQuestions1;
} else if (mode == USE_SECOND) {
listToUse = mQuestions2;
}
for (Question q : listToUse) ...
}
如果您有兩個以上,則可以使用Map
存儲問題列表:
Map<Integer, ArrayList<Question>> questionMap = new HashMap<Integer, ArrayList<Question>>();
questionMap.put(1, mQuestions1);
questionMap.put(2, mQuestions2);
questionMap.put(3, mQuestions3);
1-> ArrayList#1
2-> ArrayList#2
3-> ArrayList#3
希望我能正確回答你的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.