【總結】第四章 數組
阿新 • • 發佈:2019-01-11
src 增強for 有序集合 常用類 new ++ 二分查找 [] ava
1. 數組是相同類型數據的有序集合。
2. 數組的四個基本特點:
-- 其長度是確定的
-- 其元素必須是相同類型
-- 可以存儲基本數據類型和引用數據類型
-- 數組變量屬於引用類型
3. 一維數組的聲明方式
-- type[] arr_name; (推薦使用這種方式)
-- type arr_name[]。
4. 數組的初始化:靜態初始化、動態初始化和默認初始化。
5. 數組的長度:數組名.length,下標的合法區間[0,數組名.length-1]。
6. 數組拷貝:System類中的static void arraycopy(object src,int srcpos,object dest, int destpos,int length)方法。
7. 數組操作的常用類java.util.Arrays類
-- 打印數組:Arrays.toString(數組名);
-- 數組排序:Arrays.sort(數組名);
-- 二分查找:Arrays.binarySearch(數組名,查找的元素)。
8. 二維數組的聲明
-- type[][]arr_name=new type[length][];
-- type arr_name[][]=new type[length][length];
使用循環遍歷初始化和讀取數組
public
class
Test {
public
static
void
main(String[] args) {
int
[] a =
new
int
[
4
];
//初始化數組元素的值
for
(
int
i=
0
;i<a.length;i++){
a[i] =
100
*i;
}
//讀取元素的值
for
(
int
i=
0
;i<a.length;i++){
System.out.println(a[i]);
}
}
}
//結果
//0
//100
//200
//300
增強for循環
public
class
Test {
public
static
void
main(String[] args) {
String[] ss = {
"aa"
,
"bbb"
,
"ccc"
,
"ddd"
};
for
(String temp : ss) {
System.out.println(temp);
}
}
}
//結果
//aa
//bbb
//ccc
//ddd
冒泡排序
import
java.util.Arrays;
public
class
Test {
public
static
void
main(String[] args) {
int
[] values = {
3
,
1
,
6
,
2
,
9
,
0
,
7
,
4
,
5
,
8
};
bubbleSort(values);
System.out.println(Arrays.toString(values));
}
public
static
void
bubbleSort(
int
[] values) {
int
temp;
for
(
int
i =
0
; i < values.length; i++) {
for
(
int
j =
0
; j < values.length -
1
- i; j++) {
if
(values[j] > values[j +
1
]) {
temp = values[j];
values[j] = values[j +
1
];
values[j +
1
] = temp;
}
}
}
}
}
//結果
//[0,1,2,3,4,5,6,7,8,9]
【總結】第四章 數組