java学习——java基础(3)数组

一、数组概念

数组是用于存储一组相同数据类型的数据结构,数组是一种引用数据类型

//数组语法
数据类型 [] 变量名;

数组初始化:静态初始化与动态初始化。
数组是静态的,必须经过初始化后才可以使用,一但初始化数组长度,长度是不可以改变的。
&静态初始化:初始化时由程序员指定每个数组元素的初始值,由系统决定数组的长度
例如:
String[] names = new String[]{“孙猴子”,“唐僧”,“猪八戒”};
int [] i = {1,3,5,7,9};
&动态初始化:动态初始化就是在初始化的时候指定数组长度(这时已经分配内存)
例如:
String[] names = new String[3];
names[0]=“孙猴子”;
names[1]=“唐僧”;
names[2]=“猪八戒”;

注意:数组的元素获取方式通过索引,数组的索引从0开始;在获取数组中的元素时索引值是从0~(数组的长度-1)

二、数组练习

1.将一组数中的0排除返回新数组。

 public class ArrayDemo1{
 /**
     * 数组排0
     *
     * @param arr
     * @return
     */
    public int[] delzero(int[] arr) {
        //用于统计不为0的个数
        int index = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != 0) {
                index++;
            }
        }

        int[] newArray = new int[index++];
        index = 0;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] != 0) {
                newArray[index++] = arr[i];
            }
        }
        return newArray;
    }

    public static void main(String[] args) {
        int[] arr1 = {19, 0, 12, 24, 0, 18, 10, 0};
        int[] o = new ArrayDemo1().delzero(arr1);
        for (int p : o) {
            System.out.println("去0之后:" + p);
        }
    }
  }

2.将一组数组逆序输出

public class ArrayDemo2{
 public  int [] reverse(int [] source ){
    //创建新数组
    int newArray = new int[source];
    for(int i = 0;i < source.length;i++){
      newArray[source.length -1-i] = source[i];
    }
    return newArray;
 }
 public static void main (String [] args){
    int o = {19,0,7,4,56,7,12};
    o = new  ArrayDemo2().reverse(o);
    for(int i : 0){
       System.out.println(i + "");
    }
 }
 }

3.对一组无须数组排序

public class ArrayDemo3 {
    /**
     * 数组排序输出
     *
     * @param arr
     * @return
     */
    public int[] code(int[] arr) {
        int temp = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] < arr[j]) {
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
        }
        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {12, 34, 3, 20, 1, 61, 32, 10, 29, 66};
        int[] o = new ArrayDemo3().code(arr);
        for (int p : o
        ) {
            System.out.print("排序之后" + p + ",");
        }
    }
}

4.对一组有序数组进行二分法查找

public class ArrayDemo4{
    /**
     * 二分法查找目标数在数组中的位置
     * @param arr
     * @param starget
     * @return
     */
    public int code(int[] arr, int starget) {
        //定义搜索范围的头和尾
        int tou = 0;
        int wei = arr.length - 1;

        //定义一个索引,初始化索引位置
        int index = -1;

        while (tou <= wei){

            //定义一个中间数
            int mid = (tou + wei)/2;
            //判断目标数和中间数的关系
            if (starget > arr[mid]){
                tou = mid + 1;
            }else if (starget < arr[mid]){
                wei = mid - 1;
            }else {
                index = mid;
                break;
            }
        }
        return index;

    }

    public static void main(String[] args) {
        int [] arr = {1,3,5,7,10,12,16,18,23};
        int start = 7;
        int inde = new ArrayDemo4().code(arr,start);
        System.out.println("要查找"+start+ "的位置为:" +inde);
    }
}

三、复杂数组

java中的数组除了可以定义基本数据类型,String类型数组外,同时也可以声明自定义数组

public class student{
   int sno;
   String sname;
   String sex;
   public Student(int no,String name,String _sex){
      this.no = sno;
      this.name = sname;
      this._sex = sex;
   }
}
public class StudentDemo{
  public ststic void main(String [] args){
    Student [] stu = new Student[3];
    stu[0] = new Student(1,"李白","男");
    stu[1] = new Student(2,"王昭君","女");
    stu[2] = new Student(3,"蔡文姬","女");
    for(Student st: stu){
       Ststem.out.println(st.name+"======"+st._sex);
    }
  }
}

四、动态数组——ArrayList

由于数组为定长的数据结构,通常数组一旦定义,则长度无法修改,在实际开发中往往存在不够灵活的缺陷;因此,在java中存在一种长度可变的动态数组——ArrayList。ArrayList类是基于可变长度数组实现的,底层原理依然是数组,内部通过数组拷贝(下面会讲述)的方式实现了数组长度可变,ArrayList类提供了一系列用于操作数组中元素的方法,如下:

  • size():获取ArrayList中元素个数
  • add():向ArrayList中添加元素
  • get():获取指定索引处的元素
  • remove():删除指定索引处的元素
  • clear():清除数组中的所有元素
//示例代码
import java.util.ArrayList;

public class ArrayListDemo1 {
    /**
     * 动态数组ArrayList
     * size():获取ArrayList中元素个数
     * add():向ArrayList中添加新元素
     * get():获取指定索引处的元素
     * remove():删除指定索引处的元素
     * clear():清除数组中索引元素值
     * ·······
     * @param args
     */
    public static void main(String[] args) {
        //创建ArrayList对象  泛型(参数化类型)
        ArrayList <String> list = new ArrayList<String>();
        list.add("Hello word!!");
        list.add("你好世界");
        list.add("Hello !!");
        list.add(" word!!");
        //获取指定位置元素值
        System.out.println(list.get(1));
        //删除指定位置元素值
        list.remove(3);
        //获取容器的长度(元素个数)
        System.out.println(list.size());
        //清空集合中索引元素
        list.clear();
    }
}

完成一个动态数组(仿写ArrayList)可以存储任意值(我们这里用int)


/**
 * 自己封装一个模拟动态数组(仿ArrayList),可以存储任意值(int)
 */
public class MyArrayList {
    /**
     * 用于存储数据的核心数组
     */
    int[] arr;
    /**
     * 声明数组索引
     */
    int index;

    /**
     * 定义构造器初始化数组
     */
    public MyArrayList() {
        arr = new int[10];
    }

    /**
     * 向容器中添加元素
     */
    public void add(int i) {
        if (index == arr.length) {
            //扩容
            kuorong();
        }
        arr[index] = i;
    }

    /**
     *  扩充容量
     */
    private void kuorong() {
        //将新数字扩充到原来的1.5倍
        int[] tamp = new int[arr.length / 2 + arr.length];
        //数组拷贝
        System.arraycopy(arr, 0, tamp, 0, arr.length);
        //将新数组赋给原数组
        arr = tamp;
    }

    /**
     * 获取指定位置元素值
     * @param postion :指定位置
     * @return
     */
    public int get(int postion){
        if (postion >= index){
            System.out.println("数组下标越界");
        }
        return arr[postion - 1];
    }

    /**
     * 获取容器中元素个数
     * @return
     */
    public int size(){
        return index;
    }

    /**
     * 清除容器中所有元素
     */
    public void clear(){
        arr = new int[10];
        index = 0;
    }
}

五、多维数组

概念:可以将数组作为另一个数组的元素,即数组中的数组(二维数组,三维数组······)

int [] [] a = new int [3] [5];
int [] [] [] b = new int [3] [4] [6];
//示例代码
public class Demo1 {
    public static void main(String[] args) {
        /**
         * 二维数组初始化
         */
        int[][] i = {{1, 2, 3}, {4, 5}, {6, 7, 8, 9}};
        /**
         * 二维数组遍历
         */
        for (int j = 0; j < i.length; j++) {
            for (int k = 0; k < i[j].length; k++) {
                System.out.print(i[j][k] + " ");
            }
            //换行
            System.out.println();
        }
    }
}

注意:
多维数组的声明是通过每一维一组方括号来实现的。
当使用new来创建多维数组时,不必指定每一维的大小,而只需指定最左边维的大小就可以

//矩阵求和
public class Demo2 {
    /**
     * 矩阵求和
     * @param args
     */
    public static void main (String[] args){
        int [] [] a = {
            {10,-3,15,8},
            {12,4,46,0},
            {1,56,7,-10},
            {23,4,6,7}
        };
        int [] [] b = {
            {-1,13,5,23},
            {45,0,4,14},
            {-8,-9,16,22},
            {15,23,16,-9}
        };
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                b[i][j] = a[i][j] + b[i][j];
                System.out.print(b[i][j] + " ");
            }
            System.out.println();
        }
    }
}

模拟电影院选座

import java.util.Scanner;

/**
 * 模拟电影院选座
 * @author ljz
 *
 */
public class CineamText {
    /**
     * 声明座位数组
     */
    int[][] seats;

    /**
     * 构造器中实现行列初始化,显示座位布局
     *
     * @param row      : 行
     * @param column:列
     */
    public CineamText(int row, int column) {
        seats = new int[row][column];
    }

    /**
     * 打印座位信息
     */
    public void showSeats() {
        for (int i = 0; i < seats.length; i++) {
            for (int j = 0; j < seats[i].length; j++) {
                System.out.print(seats[i][j] + "");
            }
            System.out.println();
        }
    }

    /**
     * 启动
     */
    public void startSelect() {
        System.out.println("请输入您要选择的行数:");
        Scanner sc = new Scanner(System.in);
        int row = sc.nextInt();
        System.out.println("您选择了第" + row + "排,请继续输入您选择的列数:");
        int coulmn = sc.nextInt();
        select(row, coulmn);
    }

    /**
     * 选座
     *
     * @param r
     * @param c
     */
    public void select(int r, int c) {
        if (seats[r - 1][c - 1] == 1) {
            System.out.println("对不起,该座位已被选定,请重新选择");
        } else {
            seats[r - 1][c - 1] = 1;
            System.out.println("选座成功!您选择的是第" + r + "排,第:" + c + "位");
            showSeats();
        }
    }

    /**
     * 菜单
     */
    public void menu() {
        System.out.println("****欢迎来到我们影院,请选座*****");
        System.out.println("****[1]显示座位剩余情况*********");
        System.out.println("****[2]选座*******************");
        System.out.println("****[0]退出*****");
        command();
    }

    public void command() {
        Scanner sc = new Scanner(System.in);
        int op = sc.nextInt();
        switch (op) {
            case 1:
                showSeats();
                menu();
                break;
            case 2:
                startSelect();
                menu();
                break;
            case 0:
                System.out.println("谢谢使用,再见!");
                //系统退出
                System.exit(0);
                break;
            default:
                System.out.println("对不起,您的输入有误,请重新输入!");
                command();
                break;
        }
    }

    public static void main(String[] args) {
        new CineamText(5, 10).menu();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值