Java Reference
In-Depth Information
Chapter 7
The ArrayList Class and the enum Keyword
7.1 Introduction to the ArrayList Class ................................................... 137
7.2 Immutable Objects ..................................................................... 138
7.3 The StringBuffer Class ................................................................ 140
7.4 The Interface of an ArrayList ......................................................... 142
7.5 Introducing the enum Construct ........................................................ 144
7.6 Summary ................................................................................ 152
7.7 Syntax .................................................................................. 152
7.8 Important Points ....................................................................... 153
7.9 Exercises ................................................................................ 153
7.10 Lab ...................................................................................... 154
7.11 Project
.................................................................................. 154
The main goal of the chapter is to introduce the reader to the ArrayList class. It allows
us to create an array without specifying the size of the array. Creating an array this way is
much more convenient because the amount of main memory that is needed by the array is
automatically managed. The chapter also covers the topic of immutable objects. These are
objects that cannot be modified. Lastly, the chapter focuses on the enum construct. Unlike
a class that can merge several primitive types, an enum is used to define a type that is
restricted to a finite subset of a primitive type.
7.1 Introduction to the ArrayList Class
One limitation of arrays is that their size cannot be changed once fixed. Consider an
application that stores information about employees. Suppose that initially we do not know
the number of employees that we want to store. Maybe we can create an array of one
thousand employees? This approach has two drawbacks. First, a lot of space is allocated
that may never be used. Second, if we end up using more than one thousand employees,
then the program will crash. Therefore, a more versatile approach for managing the size of
an array is needed. The ArrayList class fulfills this task. An ArrayList of employees can
be defined as follows.
ArrayList < Employee > emps = new ArrayList < Employee > () ;
The above definition states that the variable emps refers to an array of employees. However,
it does not specify the size of the array. Note that an ArrayList is not your normal class.
It is a generic class .
A generic class takes as input the name of one or more classes as a parameter.
These classes are specified immediately after the name of the class, they are separated
by commas, and they are surrounded by angle brackets <> .
137
 
Search WWH ::




Custom Search