Chapter 4 Flashcards
Class Libraries
Java calls it “libraries”, packages.
Grouping objects is a recurring requirement
The java utility package contains classes for doing this
Requirement Group Objects
-The collection abstraction becomes a class
-The operations are methods of that class
-A particular collection like music collection would be an instance of that class
-Items stored in the instance are object
Collections
We specify:
-The type of collection: ArrayList
-The type of object it will contain:<String>
-Private
ArrayList<String>files;
we say "ArrayList of String"</String></String>
Importing
-How we gain access to lib classes
-Import statements must be placed before class distinctions
Creating an ArrayList Object
-In versions of Java prior to version 7: -files=new ArrayList<String>();</String>
-Java 7 introduced diamond notation:
-Files=new ArrayList<>();
The type of parameter can be inferred from the variable being assigned to a convenience
Features of the Collection
-Increases it capacity as necessary.
-Keeps a private count:
*size() accessor
-Keeps objects in order
-Details of how this is done is hidden
Using the Collection
public class MusicOrganizer & private ArrayList<String>files;
...</String>
public void add file (string filename) & files.add(filename):
*For adding a new file
…
public int setnumberofFiles() &
return files.sizes():
*For returning of files (Delegation)
Generic Classes
-Collections are known as parameterized or generic types
-ArrayLIst implements list functionality:
*add, set, size, etc
One type parameter says what we want a list of:
-ArrayList<Person>
-ArrayList<TicketMachine>
-Etc</TicketMachine></Person>
Index Number
-Position of an object in a collection = index
Starts at 0 & last size is -1
-Remove method can change the index value of remaining objects to fill in the gap
The General Utility of Indices
Using integers to index collections has a general utility
-‘next’ is: index +1
-‘previous’ is: index -1
-last’ is: list.size() -1
‘The first three’ are the items @ indices 0,1,2…
We could also think about accessing items in sequence:0,1,2….
Iteration Fundamentals
-We often want to perform some actions an arbitrary number of times
-Most programming languages include loop statement to make this possible
-Java has several sorts of loop statements
For- each loop pseudo code
I.e
for(ElementType element: collection) (loop body)
- for each element in collection, do the things in the loop body
- Type of loop variable must be the same as the declared element type of the collection we’re going to use
Critique of for-each loop
- only use for processing whole collection - definite iteration
- can’t stop part way
For- Each loop- search tasks are indefinite
- can’t predict, how many places we will have to look
- although there may be an absolute limit (like checking every possible location)
- infinite loops are also possible- through error or the nature of the task