Java Notes (4) - Data Structures

轉載請註明出處:http://blog.csdn.net/cxsydjn/article/details/71513576

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:

  1. Initialization:

    • The int variable named counter is initialized to the value of 0 before the loop is run.
  2. 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 to true, the code in the block will run.
    • Otherwise, if the expression evalutes to false, the for loop will stop running.
  3. Increment:

    • Each time the loop completes, the increment statement is run. The statement counter++ increases the value of counter by 1 after each loop.

Note that similar to the if-then statement, 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 add method adds new elements to the ArrayList.
  • 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 the result on the console.

  • Insertion

    • To insert new elements into an ArrayList, we can use a slightly different version of the add method.
    • object_name.add(index, element)
    • The add method adds a new element to the ArrayList at the index.
  • object_name.size()

    • The size method returns an int that represents how many total elements are stored within object_name.

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 String object allows you to store multiple characters, such as a word in quotations (e.g. "Rats!").

  • Manipulation

    • object_name.put(key, value)
    • put method to add a String key and an associated Integer value. The String key is the text inside double quotes " ". The Integer value is represented by the number.
  • Access

    • object_name.get(key)
      • In order to access a value in a HashMap, we specify the key.
  • Iterate over a HashMap

    • keySet()

      • The keySet method of HashMap returns a list of keys.
      • Inside the loop, we access the current key and use the get method of HashMap to access the value.
      for (String item : object_name.keySet()) {
      
      }

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));

        }

    }
}

External Resources

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章