Using the Array List Class
Overview
Some people love to collect things. My wife collects lots of things: Salt and pepper shakers, nutcrackers, bears, shot glasses, and tin signs to name but a few.
If I were writing a program to keep track of one of her collections, an array would be a poor choice for storing the data. That's because on any given day, she may come home with a new item she found at an estate sale or an auction. So if she had 87 tin signs before, and I had created an array big enough to hold all 87 signs, I'd have to change the array declaration to hold 88 signs.
Java's collection classes are designed to simplify the programming for applications that have to keep track of groups of objects. These classes are very powerful and surprisingly easy to use-at least the basics, anyway. The more advanced features of collection classes take some serious programming to get right, but for most applications, a few simple methods are all you need to use collection classes.
Unfortunately, Java's collection classes are organized according to a pretty complicated inheritance hierarchy that can be very confusing for beginners. Most of the Java books I have on my shelf start by explaining this inheritance scheme and showing how each of the various collection classes fits into this scheme, and why.
I'm not going to do that-I think it's very confusing for a newcomer to collections to have to wade through a class hierarchy that doesn't make sense until you know some of the details of how the basic classes work. So (instead), I just show you how to use two of the best of these classes. In this chapter, you find out how to use the ArrayList class. Then, in the next chapter, you find out how to use its first cousin, the LinkedList. Once you know how to use these two classes, you shouldn't have any trouble learning how to use the other collection classes from the API documentation.
TECHNICAL STAUFF | Java 1.5 introduced a major new language feature called generics that is aimed specifically at making collections easier to work with. Because generics are an integral part of how collections work in Java 1.5 and Java 1.6, I incorporate the generics feature into this chapter from the very start. I point out the differences for using ArrayList without generics along the way, just in case you're using an older version of Java or are working with programs that were written before Java 1.5 became available. (For a complete explanation of how the generics feature works, you can refer to Book IV, Chapter 5.) |