You are on page 1of 19

Topic 5

ARRAY

1
Mục tiêu bài học

• Khai báo, khởi tạo mảng 1 chiều


• Sử dụng mảng args[] của main method
• Sử dụng các vòng lặp for, while, do-while
• Array copy
• Array sort
• Array of object
• Sử dụng lệnh “for each”

2
One-dimensional Array

• An array is a data structure that stores a collection of values


of the same type
• Declare
int[] a; // formal
int a[];
• instantiating
int[] a = new int[3];

int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };

3
For loop

• Cú pháp
for(initialization statements; condition; increment
statements)
{
action statements;
:
:
}

4
While loop

 Cú pháp
while(condition)
{
action statements;
:
:
}
• Therefore, the code in the block may never be executed. If
you want to make sure a block is executed at least once, you
will need to move the test to the bottom. You do that with the
do/while loop
5
Do-while loop

• Cú pháp
do
{
action statements;
:
:
} while(condition);

6
Break

• Lệnh break trong Java được sử dụng theo 2 cách:


– Nó được sử dụng để kết thúc một case trong câu lệnh switch
– Nó được dùng để kết thúc vòng lặp ngay lập tức. Nếu trong câu lệnh
loop mà gặp phải break thì vòng lặp sẽ kết thúc ngay lập tức, các câu
lệnh sau break trong vòng lặp sẽ bị bỏ qua.

7
Initializing

int[] a = new int[100];


for (int i = 0; i < 100; i++)
a[i] = i; // fills the array with 0 to 99
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);

• The “for each” Loop


for (variable: collection) statement
for (int element : a)
System.out.println(element);
• Replace by while, do-while

8
Using the String args[]

public class Message


{
public static void main(String[] args)
{
if (args[0].equals("-h"))
System.out.print("Hello,");
else if (args[0].equals("-g"))
System.out.print("Goodbye,");
// print the other command-line arguments
for (int i = 1; i < args.length; i++)
System.out.print(" " + args[i]);
System.out.println("!");
}
}
java Message -g cruel world
Goodbye, cruel world!
9
Array copying

int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };


int[] luckyNumbers = smallPrimes;
luckyNumbers[5] = 12; // now smallPrimes[5] is also 12
• If you actually want to copy all values of one array into a
new array, you use the copyTo method in the Arrays class:
int[] copiedLuckyNumbers
= java.util.Arrays.copyOf(luckyNumbers, luckyNumbers.length);

luckyNumbers
= java.util.Arrays.copyOf(luckyNumbers, 2 * luckyNumbers.length);
The additional elements are filled with 0 if the array contains numbers, false if
the array contains boolean values.
10
Array copying (cont)

• Prior to Java SE 6
System.arraycopy(from, fromIndex, to, toIndex, count);

int[] smallPrimes = {2, 3, 5, 7, 11, 13};


int[] luckyNumbers = {1001, 1002, 1003, 1004, 1005, 1006, 1007};
System.arraycopy(smallPrimes, 2, luckyNumbers, 3, 4);
for (int i = 0; i < luckyNumbers.length; i++)
System.out.println(i + ": " + luckyNumbers[i]);

Ouput: 0: 1001
1: 1002
2: 1003
3: 5
4: 7
5: 11
6: 13

11
Array order

• To sort an array using method sort(type[] a)


– sorts the array, using a tuned QuickSort algorithm.
– sorts array of primitive variable.
– sorts array of object.
• Example:
int[] smallPrimes = {13, 7, 5, 11, 3, 1};
Java.util.Arrays.sort(smallPrimes);
for (int i = 0; i < smallPrimes.length; i++)
System.out.print(smallPrimes[i] + “, ”);
=> 1 3 5 7 11 13

12
Array of Object

• Mảng không chỉ để lưu các kiểu dữ liệu nguyên thủy


• Mảng có thể lưu đối tượng
• Cú pháp khai mảng mảng đối tượng:
ClassName[] arrayName
• Khởi tạo mảng đối tượng:
arrayName = new ClassName[length]
for (int i = 0; i< length; i++) {
arrayName[i] = new ClassName();
}

13
Two-dimensional Array

• Declare
double[][] balances; // double balances[][]; ??
• Instaning
balances = new double[NYEARS][NRATES];
int[][] magicSquare =
{
{16, 3, 2, 13},
{4, 15, 14, 1}
};
• Initializing
for (int i = 1; i < balances.length; i++) {
for (int j = 0; j < balances[i].length; j++) {
balances[i][j] = oldBalance + interest; }}
14
“for each” loop

• Use “for each” loop syntax:


for (double[] row : a)
for (double value : row)
do something with value
• System.out.println(Arrays.deepToString(a));
[[16, 3, 2, 13], [5, 10, 11, 8], [9, 6, 7, 12], [4, 15, 14, 1]]

15
ArrayList

• ArrayList là một phiên bản thông minh hơn của mảng.


Thuộc không gian tên System.Collection.ArrayList
• So sánh ArrayList và Array:
– Kích thước mảng cố định theo khai báo còn ArrayList có thể
thay đổi theo yêu cầu.
– Nếu mảng cần định kích thước, gán trị thì ArrayList cung
cấp các phương thức cho phép thêm, chèn, xóa một phần tử
trong tập hợp.
– Các phần tử của mảng phải cùng một kiểu dữ liệu, còn các
phần tử của ArrayList có kiểu chung là Object, nghĩa là có
thể có các kiểu khác.

16
ArrayList (tiếp)

17
Understanding variable scope

• Phạm vi hoạt động của biến trong vòng lặp for


• Ví dụ:
public class MainClass {

public static void main(String[] args) {


for (int x = 0; x < 5; x++) {
System.out.println(x);
}
System.out.println(x);
}

18
Tổng kết

• Khai báo, khởi tạo mảng một chiều


• Sử dụng mảng args của main method
• Các vòng lặp for, while, do-while
• Sử dụng vòng lặp với mảng
• Array copy
• Array sort
• Array of object
• Sử dụng lệnh “for each”
• Khai bảo, khởi tạo mảng hai chiều.

19

You might also like