Data Objects
Last modified Wednesday, 23-Oct-2024 01:03:11 UTC.
- Bundles of Data (like wot C programmers call structs)
- Enumerated classes
- These are useful for data that has a fixed number of possible values.
- A fixed number of predefined objects
- The advantage is that it prevents inappropriate values being assigned to the variables.
- The values() class method returns an array of the values.
- Individual values are available from the class
- null is always a possible value for an enumerated variable.
- The valueOf() class method converts a string to an enum value.
- Example: EnumSeason.java
- Much more can be done with enumerated classes, e.g., adding data
to be associated with each of the values.
- Wrapper Classes
- ArrayLists
- Arrays are of a fixed size, that has to be known at the time of
creation.
If the number of elements is unknown, the maximum has to be
catered for, and possibly much of an array is then unused.
- ArrayLists are like arrays, but can be resized.
ArrayLists grow their capacity on demand.
- ArrayLists point to objects of a specified type, not
primitive data (but wrappers can solve that :-)
- ArrayLists are defined in java.util
- ArrayList methods include:
- add method adds an object to the array, either at a
specified position or the end if unspecified.
The array list is enlarged if necessary.
- get returns the element at a specified position
- set sets the value at a given position
- size returns the number of elements in use
- indexOf searches the array list for an object
- Example:
UseArrayList.java
Exercises
Exam Style Questions
- Write a program that prints out the sum of its command line parameters.
Assume that all the parameters will be valid integers (as strings).
- Write a program that repeatedly prompts the user for a character, reads
it, wraps it in a Character object, and adds it to an
ArrayList of objects.