For Loop
The for loop repeatedly runs a block of code until a specified condition is met.
The example below shows how a for loop is used:
|
|
The statements within the parentheses of for loop compose the following parts:
Initialization: the
int
variable namedcounter
is initialized to the value of0
before the loop is run.Test condition: the Boolean expression
counter < 5
is a conditional statement that is evaluated before the code inside the control statement is run every loop. If the expression evaluates totrue
, the code in the block will run. Otherwise, if the expression evaluates tofalse
, the for loop will stop running.Increment: Each time the loop completes, the increment statement is run. The statement
counter++
increases the value ofcounter
by1
after each loop.
ArrayList
The ArrayList stores a list of data of a specified type. Let’s go through an example of how to create, or declare, an ArrayList of type Integer
.
|
|
ArrayList is a pre-defined Java class. To use it, we must first create an ArrayList object.
In the example above, we create an ArrayList object called quizGrades
that will store data types belonging to the <Integer>
class (whole numbers).
Manipulation
Let’s add some values of type Integer
to the ArrayList, one by one, like this:
|
|
In the example above, we call the add
method on quizGrades
. The add
method adds integers to the ArrayList. The values 95
, 87
, and 83
are added to the list.
Access
Here is an example of accessing the element in the first position of the list:
|
|
The example above will print out the grade value of 95
.
Insertion
To insert new elements into an ArrayList, we can use a slightly different version of the add
method that you previously used:
|
|
Iterating over
Earlier in this lesson, we learned about the for loop. Since we’ve also learned how to retrieve the value at a specific index of an ArrayList, we can now access each of the elements.
|
|
For Each Loop
Here is an example of the concise for each loop:
|
|
HashMap
Another useful built-in data structure in Java is the HashMap.
Although the name of the data structure might not make sense to you immediately, think of it as a real-life dictionary. A dictionary contains a set of words and a definition for each word. A HashMap contains a set of keysand a value for each key.
If we look up a word in a dictionary, we can get the definition. If you provide a HashMap with a key that exists, you can retrieve the value associated with the key.
Declaring a HashMap is shown in the following example:
|
|
Manipulation
Add keys and values to a HashMap:
|
|
Access
To access data in an ArrayList, we specified the index. In order to access a value in a HashMap, we specify the key:
|
|
Iterating over
We can also access properties of a HashMap, such as the number of entries or the contents of the HashMap.
Let’s access the length and print out the contents of the myFriends
:
|
|