Reputation: 65
I have a java program which uses multiple HashMaps, one for each "category" of order made in an hypothetical restaurant.
I need to do some processing and output text to a file. However, I have gone the "bad" way and simply wrote the code six times, calling a different hashmap in each of the times.
I cannot leave exact demo code as this will be delivered as a project and as such could be found by random plagiarism finders, and mistakenly marked as plagiarism since it'd be a huge chunk of code. However, the following should sort of illustrate the problem.
DoSomething(These);
DoSomething(All);
DoSomething(Have);
DoSomething(Completely);
DoSomething(Different);
DoSomething(Names);
Now instead of "DoSomething", imagine having 20 lines of code, and for each 20 lines I use one specific HashMap.
I can't exactly populate an array and make it use the data from the Array, as it'll attempt to use Strings instead of the HashMap (calling DoSomething("These") instead of DoSomething(These)).
Is there any way to call the HashMaps dynamically, so that I can shorten all this into just one single loop that does the same thing for each of the HashMaps?
Upvotes: 0
Views: 117
Reputation: 1675
If you have a couple hashmaps, lets say:
HashMap<String, String> aMap;
HashMap<String, String> anotherMap;
You could then populate a new ArrayList with these, like so:
List<HashMap<String, String>> myMaps = new ArrayList<>();
myMaps.add(aMap);
myMaps.add(anotherMap);
With this, you can iterate through your maps using an enhanced for loop:
for (HashMap map : myMaps) {
//code goes here
}
A benefit here is that your list is dymanically sized, therefore you can add and remove hashmaps from it as you please.
Upvotes: 3
Reputation: 841
I am not sure based on your question what the DoSomething-method is supposed to do though, but I understood it as if it is supposed to return a certain HashMap depending on a certain order category that is provided as a String. In this case you could just make a HashMap of HashMap, with a String key for the first HashMap. Depending on the Sting key provided you would then obtain the corresponding HashMap.
Upvotes: 0
Reputation: 16932
It sounds like it's time to do some refactoring.
Upvotes: 1
Reputation: 9872
If every chunk of your code is so similar, an IDE like eclipse can easily recognize it and refactor
it to 6 calls to "DoSomething" with a Map parameter.
If you have not such an IDE... do the same by hand, it is not that hard and will pay off (you actually don't want to maintain that mess and fix your errors or make your times x6 times through your code)
Upvotes: 0