Java - factory method, encapsulation, hashmap example
Archive - Originally posted on "The Horse's Mouth" - 2014-11-27 18:30:43 - Graham Ellis
Many of the Java examples on our web site that are used to illustrate the utility classes in Java.util are written using String objects as both key and value - however, on the Java course just completed I wrote a somewhat more complex examples to show the relationship between various aspects of the language.
Using a buffered reader, I've read in a series of records from a file and passed each one on to a factory method which analyses that text string and returns an object. Using an accessor method, I extract a text key that I'm going to use to key that object, and I then add the object into a HashMap. See the source code at [here].
The internals of how the input string is converted into an object, and how the properties are accesses, is encapsulated in the class, using a factory method and conventional accessors - see [here].
Once the has map has been set up, my sample program picks out and reports on a chosen element by its key, and I've also demonstrated a set and an iterator to parse the whole Hashmap.
This week, I ran a private Java course for five delegates - 4 days of "Learning to program in Java" - and I thoroughly enjoyed myself. I'm delighted to run such basics courses in Java, although there are so many specialist advanced libraries in Java that we can rarely cover individual customer's detailed specialist requirements these days - hence we no longer offer a standard public course. But please ask if interested!