move_slow_break_things
move_slow_break_things

Reputation: 847

HashMap multiple keys to one element

I couldn't think of a better title to the problem but my question isn't really with mapping two different keys to one value. I know how to do that. My question is, is there a way to have a specific key-key pair map to a value?

For example, I'm trying to implement an online grading system. This database has the exams keyed by their examId. "Midterm 1" maps to Midterm1 exam instance. There is also a solution manual for every exam. Then I want to add a student's answer sheet to the database and compare the student's answer to the solutions manual to calculate the score.

I'm implementing the AnswerSheet class and am stumped by this problem. A student's answer corresponds to a certain problem on a certain exam. Is there a way to have examId and questionNumber (combined) be a key that maps to the answer the student wrote down? It wouldn't be enough to just map the question number to the answer as question 1 on midterm 1 is not the same as question 1 on midterm 2. I am trying to think of a way to have this:

exam1 question1 ---------> "Student Answer for exam 1"

exam1 question5 ---------> "Student Answer for exam 1"

exam2 question1 ---------> "Student Answer for exam 2"

I hope I have adequately explained my conundrum. Hopefully someone can point me in the right direction.

Upvotes: 0

Views: 285

Answers (2)

Ken Geis
Ken Geis

Reputation: 922

Check out the class Table in Guava.

A collection that associates an ordered pair of keys, called a row key and a column key, with a single value.

If you don't want to use Guava, you can just use a List (such as ArrayList) to contain the two keys and then use that composite key to access your map. See List.equals(..) and List.hashcode() to see that they do the right thing to enable this.

Upvotes: 0

chrisl08
chrisl08

Reputation: 1658

Assuming that "exam", "question" and "Student Answer" are objects mapped to the database through your ORM, and they each have a primary key, you can concatenate the 2 primary keys of "exam" and "question" into a string value, and use this value to store "Student Answer". Something like this:

//built a hash key using primary keys of objects
String hkey= "EXAM:" + exam.examId().toString() + 
             "-QST:" + question.questionId().toString();

map.put(hkey, studentAnswer);

Note that you need the prefixes "EXAM:" and "QST:" just in case you have primary key number collisions.

Upvotes: 1

Related Questions