数组

来源:互联网 发布:淘宝飞猪靠谱吗 编辑:程序博客网 时间:2024/06/06 18:08

数组Array

声明方法:

一维数组:    数组类型[]<数组名> =new 数组类型[长度]或者{数组元素类型以“,”隔开}二维数组:    数组类型[][]<数组名> = new数组类型[][]或者{{},{},{},{}}    数组储存的不仅仅是基本数据类型,也可以是自定义类型。

数组的访问和修改是通过下标完成的,下标从0开始,数组的的大小是固定的。如果想扩容,则需要新建一个数组,将原数组拷贝进去。
新建一个数组如果没有进行赋值则访问的是当前类型的默认值。
String类型遍历输出,for方法:

String[] strs = { "唐僧","孙悟空","猪悟能","沙悟净" };for(String str :strs ){System.out.println("  " + str);}

数组最经常遇见的异常:数组下标越界异常ArrayIndexOutOfBoundsException

数组排序最常用的两个排序法

1.插入排序
插入排序还有升级版希尔排序

public static void insertSort() {        int array[] = { 10, 15, 589, 65, 425, 12, 38, 59, 56438 };        int l = array.length;        for (int i = 1; i < l; i++) {            int get = array[i];            int j = i - 1;            while (j >= 0 && array[j] > get) {                array[j + 1] = array[j];                j--;            }            array[j + 1] = get;        }        for(int i = 0;i<l;i++){            System.out.print("  "+array[i]);        }    }

2..冒泡排序
冒泡排序还有升级版鸡尾酒排序

public class maopaopaixufa {    public static void main(String[] args) {        int array[] = { 10, 15, 589, 65, 425, 12, 38, 59, 56438 };        int l = array.length;        for (int i = 0; i < l; i++) {            for (int j = 0; j < l-i-1; j++) {                if(array[j]>array[j+1]){                    switchData(array,j,j+1);                }            }        }        for(int i = 0;i<l;i++){            System.out.print("  "+ array[i]);        }    }    private static void switchData(int array[], int i, int j){        int temp = array[i];        array[i] = array[j];        array[j] = temp;    }}