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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值