Until today we have used plain arrays to store arrays of numbers and Strings. Lab#3 will review the syntax and semantics of plain arrays as well as the use of the Arrays library to sort and search plain arrays.
Lab#3 will also introduce you to the ArrayList class - a self resizing, self managing, object that contains a plain array but takes away your ability to directly index [] into the underlying plain array and instead gives you several methods to call that allow you to add and retrieve values into and from the underlying array. An ArrayList is thus just a plain array bundled together with a bunch of methods that allow you to add/get values to/from the array plus many other operations. This underlying array and methods are wrapped up in an object called an ArrayList. ArrayLists keep track of the count which you can retrieve via a call to .size(). ArrayLists also enforce the array discipline for you keeping all values packed tight to the front.
Plain arrays have a library of search and sort methods, Arrays library
ArrayLists have a library of search and sort methods too: Collections library
CORRECT FORMS OF DECLARATION | UNDISCIPLINED FORMS OF DECLARATION |
---|---|
ArrayList<String> words; ArrayList<String> words = null; ArrayList<String> words =new ArrayList<String>(); |
ArrayList words; ArrayList words = null; ArrayList words =new ArrayList(); |
ArrayList | plain array | Maintains count for you every time you .add() / .remove() etc. Count gotten by calling: .size() | User maintains count. |
---|---|
Automatically allocates space for 10 elements by default. | User must specify initial capacity. Once specified can never change. |
Automatically doubles (or X 1.5 depending on implementation) when its capacity when full. | User must watch for array filling up and take action to avoid overflow. |
Enforces array discipline by keeping all values packed to front of array - even after a removal. | Does not enforce array discipline. Allows you to store elements non-contiguously. |
Illustrates a method .toCharArray()
built into every String.
See Java 22 API for String. This built in String method extracts the letters of the String and puts them into a plain array of char. This plain array of char is full - i.e. the array is just long enough to hold the exact number of letters from the String. There is no need for a count value. The .length of the array is the count of chars in the array.
C:\>java Lab3 jumbles.txt