This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Set up a Question class (or change Question to String throughout)
You need a HashMap to hold Questions as V=values using Integers as your K=keys.
Declare a Map<Integer, Question> questionMap object as a field
Initialise it as a HashMap<Integer, Question> in your constructor. No need for constructor arguments
Set up an int field and call it counter or similar. Initialise it to 1 in the constructor.
Set up an "addQuestion(Question q)" method.
In that method, whenever a Question is sent, use the method of questionMap which inserts members, using "counter++" and "q" as the two things to put in. Counter will probably be converted to an Integer object by auto-boxing, so you don't have to say "new Integer(counter++)"
Set up a printQuestion(int number) method.
In that method use the questionMap method which returns the "V" using "number" as the argument.
Easy.
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32833
4
posted
0
Both of you have managed to misread the lettering in the Map<K, V> interface; both have written map.put(question, counter) or Map<String, Integer>. It ought to be put(counter++, question) or Map<Integer, Question>.
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1707
posted
0
Hi Campbell,
Didn't you see my following line,
Instead of making key your question why don't you do vice versa.
Even writing Map<String,Integer> or HashMap<String,Integer>, I dont see any problem in them. Can't String be a Key? Why not?
Correct me, if wrong.
cmbhatt
Chandra Bhatt
Ranch Hand
Joined: Feb 28, 2007
Posts: 1707
posted
0
How my previous descriptive post not complete. Some 10 lines were also there where I had another solution. Devil ate it.
It was :
Is that OK?
Regards, cmbhatt
Avinash Sridhar
Greenhorn
Joined: Apr 11, 2007
Posts: 6
posted
0
Thanks a lot for the useful insight. I will try them out and see whether I can print them on the console
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32833
4
posted
0
Thank you, Chandra Bhatt. Yes, you do usually use String as the "K" variable in a Map, but here Avinash Sridhar specifically said he wants the questions to be numbered, so the number (int or Integer) would be the "K." You want to enter "No 1" and get "How do you insert into a HashMap?" rather than vice versa.