1. 数组的基本知识:数组是用来存储变量的集合
2. 数组的声明格式:元素类型 [] 数组引用变量名 = new 元素类型[元素个数]
如: int [] arrary = new int [10] 声明并创建一个具有int类型的10个元素 arrary 是一个含有十个int 类型的元素数组的引用变量
3. 数组初始化:
int [] arrary = new int [] {1,2,3,4,56,7};
或 int [] arrary = new int [6];
arrary [0] = 1;............arrary [5] = 7;
或 int [] arrary = {1,2,3,4,56,7};
3. for each 循环 : 不使用下标就可以顺序遍历整个数组
for ( double u : mylist ) {
System.out.println (u);
} //对mylist中的每个元素进行以下操作
4. 复制数组的三种方法:
1) 使用循环语句逐个复制数组元素
如:int arrary1 [] = {1,2,3,4,5,6};
int arrary2 [] = new int [arrary1.length];
for (int i = 0; i < arrary1.length; i ++){
arrary2 [i] = arrary1 [i];
}
2)使用System类中的静态方法arraryCopy
3)使用clone方法复制数组
5. 给方法传递数组
public static void printArrary(int [] arrary){
for (int i = 0; i < arrary.length){
System.out.println(arrary [i]);
}
}
public static void main ( String [] args){
int [] getArrary = {1,2,3,4,5};
printArrary(getArrary);
}
6. 选择排序法
先找到数组中最小的的数,然后把它放在数列的第一位。接下来在剩下来的数中找到最小数放在第一个数的后面,以此类推直到仅剩下一个数为止。
如:
class Exerc05{
public static void selectSort(int []arrary1){
for (int i = 0; i<arrary1.length-1; i++){ for (int j = i + 1; j<arrary1.length; j++){ if (arrary1[i] > arrary1[j]){ int temp = arrary1[i]; arrary1[i] = arrary1[j]; arrary1[j] = temp; } } } } public static void printArrary(int[] arrary3){ System.out.print("["); for (int k = 0; k<arrary3.length; k++){ if (k!= arrary3.length - 1){ System.out.print(arrary3[k] + ","); } else System.out.println(arrary3[k] + "]"); } } }
class Exerc06{ public static void main(String[]args){ Exerc05 arr = new Exerc05(); int[] arrary2 = {1,3,6,7,2,9}; //int arr1 = arr.selectSort(arrary2);不能将一个数组赋值给一个变量;编译报错; //排序前打印 arr.printArrary(arrary2); //System.out.print(arr1); arr.selectSort(arrary2); //排序后打印 arr.printArrary(arrary2); } }