Labels

Sunday, March 6, 2016

JAVA基础回顾 Part IV:JAVA数据结构

Jinhai‘s JAVA cheat sheet

Codecademy学习笔记 Part IV

for循环 for loop

for (int counter = 0; counter < 5; counter++) {

    System.out.println("The counter value is: " + counter);

}

for循环里有以下几个部分
  • 初始化(initialization): the int variable named counter is initialized to the value of 0 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 to true, the code in the block will run. Otherwise, if the expression evalutes to false, the for loop will stop running.
  • 增量(increment): Each time the loop completes, the increment statement is run. The statement counter++ increases the value of counter by 1 after each loop.

ArrayList

声明ArrayList (Declaring an ArrayList)
ArrayList<Integer> quizGrades = new ArrayList<Integer>();
对ArrayList的操作(Manipulation)
增加元素add
ArrayList<Integer> quizGrades = new ArrayList<Integer>();
quizGrades.add(95);
quizGrades.add(87);
quizGrades.add(83);
取出(Access)元素
System.out.println( quizGrades.get(0));
插入(Insertion)元素
quizGrades.add(0, 100);//add(index,data)


注意:在原本index为0的地方插入
遍历ArrayList(Iterating over an ArrayList)
for (int i = 0; i < quizGrades.size(); i++) {

    System.out.println( quizGrades.get(i) );

}

或者使用for each loop
取出(Access)元素
for (Integer temperature : weeklyTemperatures) {

    System.out.println(temperature);

}

散列表(HashMap)

类似于Python里的dictionary
声明 HashMap (Declaring a HashMap)
HashMap<String, Integer> myFriends = new HashMap<String, Integer>();
增加元素put
HashMap<String, Integer> myFriends = new HashMap<String, Integer>();
myFriends.put("Mark", 24);
myFriends.put("Cassandra", 25);
myFriends.put("Zenas", 21);
取出(Access)元素
System.out.println( myFriends.get("Zenas") );//output is 21

遍历HashMap(Iterating over a HashMap)
HashMap的keySet方法返回一个键值列表(a list of keys)
System.out.println( myFriends.size() );
for (String name: myFriends.keySet()) {
    System.out.println(name + " is age: " + myFriends.get(name));
}

JAVA数据结构总结

  • for循环 For Loops: used to repeatedly run a block of code
  • for each循环 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

1 comment: