Java Utility class - flexible replacement for array. Also cacheing in objects and multiple catch clauses example.
Archive - Originally posted on "The Horse's Mouth" - 2015-01-16 15:50:45 - Graham EllisIn Java, utility class objects are used as flexible alternatives to arrays to hold collections of other obejcts. ArrayLists and Vectors hold an ordered (indexed) set of other objects, but due to the structure used in memory, there's no need to know how many items there are going to be in the collection when you start. So that makes them excellent for appications which read from a stream of data (file, keyboard, socket, URL etc) and store all (or some) or the data read (typically as objects for later processing.
From this week's Java course, an example [here] in which I've commented out much of the code that I used for an earlier iteration (with an array) and replaces it with a Vector. You'll note that I've had to move away from the [] notation that's used with arrays, and move to methods so that (for example)
places[nStations] = current;
is replaced by
places.addElement(current);
Although this might look like a retrograde step if you're doing straightforward code conversion, if you refactor as you more on to a vector you'll find other savings such as the saving of the need to keep count of the number of elements you have in your collection. With an array you had the number of elements occupied to keep a track of yourself AS WELL AS the separate length (= capacity) within the program. Once you've moved on to a vector, the size() method tells you all.
The Station class used in the example mayt be found [here]. Note that I've used this to illustrate the caching of calculation results - a simple division in this case but it could have been complex calculations and database and other resource references we didn't want to repeat. The caching design pattern allows for the calculation to be saved from repitition whether you have an application that creates huge numbers of objects but only calculates from a few, or creates a few objects and calculates (or at least enquires of) the all many times.
Finally, note that the exception handler in the main code catches two different types of exceptions in two different ways - a good example of the need for multiple catches. Well, if you look carefully it was an excellent example in an earlier iteration of my appliaction when I was using an array - in the latest code as the end of my demonstration, the replacement of the fixed length array with a Vector has meant that there's no longer any need to catch an overflow ... the vector expamds dynamically!
As an aside, another slight "down" on Vectors, ArrayLists, etc, is that they can only hold objects not primitives. In practical use, it turns out not to be a huge problem as you're likely to be handling collections of objects for the most part anyway. And if you really want to hold ints,for example, you could always hold Integer objects.