I am new to Java and i am currently rewriting a Perl code in Java.
In Perl i have a Hash of Hash like
$hashref->{index1}->{index2}->{index3} = $value;
In this i store the index1 , index2 , and index3 in 3 separate hashes along with above hash.
Also Index1 and index2 are of type long and index3 is String.
Now i want to rewrite the similar stuff in Java.
So i came up with 2 ways
1)HashMap<Long, HashMap<Long ,HashMap<String,String> >>
2)HashMap<String, String> //In this approach i concatenate index1,index2 and index3 using _ and make a single string
I want to know which way will be efficient as max of 100 keys for index1, 300 keys for index2 and 700 keys for index3 is possible.
First, let’s discuss #2
It doesn’t work 100% of the time due to possible ambiguity if the index strings can contain the separator character (“_”):
E.g. consider 3 sets of indexes: (“12”, “13_13” and “14”) and (“12_13”, “13” and “14”). They both produce the same concatenated key.
It doesn’t allow straightforward processing of the 2-d and 3-d level hashes as data structures easily.
E.g. you can not easily do Java equivalent of “
keys %{$hash->{index1}}” – find all the keys for a hash of second level stored under index1. It’s doable, but much harder. Or “delete $hash->{index1}“.If these 2 considerations don’t bother you, using a concatenated key for 1-level HashMap is fine.
If they do, you need to do #1 – a fairly robust implementation was posted on SO previously:
” Java equivalent of Perl's hash ” . Please note that such implementation is NOT trivial, and therefore your alternate approach of concatenated 1 level of indexes is a very good alternative.