The note introduces how to create, manipulate, and store information in data structures in Java.
Java notes of open courses @Codecademy.
For Loop
Typical For Loop
Java conveniently provides control statements to run a task repeatedly. One of control statements is for loop, which could help us manipulate an entire set of data.
The for loop repeatedly runs a block of code until a specified condition is met.
//A for-loop example
for (int counter = 0; counter < 5; counter++) {
System.out.println("The counter value is: " + counter);
}
The statements within the parentheses of for loop compose the following parts:
-
Initialization:
- The
intvariable namedcounteris initialized to the value of0before the loop is run.
- The
-
Test condition:
- The Boolean expression
counter < 5is a conditional statement that is evaluated before the code inside the control statement is run every loop. - If the expression evaluates to
true, the code in the block will run. - Otherwise, if the expression evalutes to
false, the for loop will stop running.
- The Boolean expression
-
Increment:
- Each time the loop completes, the increment statement is run. The statement
counter++increases the value of counter by1after each loop.
- Each time the loop completes, the increment statement is run. The statement
Note that similar to the
if-thenstatement, no semicolon is necessary.
For Each Loop
Since most for loops are very similar, Java provides a shortcut to reduce the amount of code required to write the loop called the for each loop.
for (Integer grade : quizGrades){
System.out.println(grade);
}
In the example above, the colon (:) can be read as "in". The for each loop altogether can be read as "for each Integer element (called grade) in quizGrades, print out the value of grade."
The loop will print out the value of each Integer element in quizGrades.
Note: the for each loop does not require a counter.
ArrayList
The ArrayList stores a list of data of a specified type.
ArrayList is a pre-defined Java class. To use it, we must first create an ArrayList object.
ArrayList<Integer> object_name = new ArrayList<Integer>();
-
Manipulation
-
object_name.add(element)- The
addmethod adds new elements to the ArrayList.
- The
-
-
Access
object_name.get(index)- We can access the elements of the object by using an element's index, or position, in the list. An element's index refers to its location within an ArrayList. - ArrayLists in Java are zero-indexed, which means that the first element in an ArrayList is at a position of
0.
Note:
System.out.println(result)prints out theresulton the console.
-
Insertion
- To insert new elements into an ArrayList, we can use a slightly different version of the
addmethod. object_name.add(index, element)- The
addmethod adds a newelementto the ArrayList at theindex.
- To insert new elements into an ArrayList, we can use a slightly different version of the
-
object_name.size()- The
sizemethod returns anintthat represents how many total elements are stored withinobject_name.
- The
HashMap
Another useful built-in data structure in Java is the HashMap. We can 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 keys and 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:
HashMap<String, Integer> myFriends = new HashMap<String, Integer>();
In the example above, we create a HashMap object called myFriends. The myFriends HashMap will store keys of String data types and values of type Integer.
Note: the
Stringobject allows you to store multiple characters, such as a word in quotations (e.g."Rats!").
- Manipulation
object_name.put(key, value)-
putmethod to add aStringkey and an associatedIntegervalue. TheStringkey is the text inside double quotes" ". TheIntegervalue is represented by the number.
-
Access
-
object_name.get(key)- In order to access a
valuein a HashMap, we specify thekey.
- In order to access a
-
-
Iterate over a HashMap
-
keySet()- The
keySetmethod of HashMap returns a list of keys. - Inside the loop, we access the current
keyand use thegetmethod of HashMap to access thevalue.
for (String item : object_name.keySet()) { } - The
-
Review
- For Loops: used to repeatedly run a block of code
- For Each Loops: a concise version of a for loop
- ArrayList: stores a list of data
- HashMap: stores keys and associated values like a dictionary
A Comprehensive Example
import java.util.*;
public class GeneralizationsD {
public static void main(String[] args) {
ArrayList<String> sports = new ArrayList<String>();
sports.add("Football");
sports.add("Boxing");
for(String sport : sports) {
System.out.println(sport);
}
//Major cities and the year they were founded
HashMap<String, Integer> majorCities = new HashMap<String, Integer>();
majorCities.put("New York", 1624);
majorCities.put("London", 43);
majorCities.put("Mexico City", 1521);
majorCities.put("Sao Paulo", 1554);
for ( String city : majorCities.keySet() ) {
System.out.println(city + " was founded in " + majorCities.get(city));
}
}
}












网友评论