數據結構(一)_數組


數組基本知識

數組對於每一門編程語言來說都是重要的數據結構之一,當然不同語言對數組的實現及處理也不盡相同。
Java語言中提供的數組是用來存儲固定大小的同類型元素。

public class Demo1 {
	public static void main(String[] args) {

		// 定義一個數組,保存五名學生的成績
		int[] scores = { 78, 93, 97, 84, 63 };

		// 輸出數組中的第二個成績
		System.out.println("數組中的第2個成績為:" + scores[1]);
	}

}

數組的基本使用

1、 聲明數組

語法: 數據類型[ ] 數組名;

或者 數據類型 數組名[ ];

其中,數組名可以是任意合法的變量名,如:

2、 分配空間

簡單地說,就是指定數組中最多可存儲多少個元素

語法: 數組名 = new 數據類型 [ 數組長度 ];

其中,數組長度就是數組中能存放元素的個數,如:

話說,我們也可以將上面的兩個步驟合並,在聲明數組的同時為它分配空間,如:

3、 賦值

分配空間后就可以向數組中放數據了,數組中元素都是通過下標來訪問的,例如向 scores 數組中存放學生成績

4、 處理數組中數據

我們可以對賦值后的數組進行操作和處理,如獲取並輸出數組中元素的值

在 Java 中還提供了另外一種直接創建數組的方式,它將聲明數組、分配空間和賦值合並完成,如

它等價於:

使用循環操作 Java 中的數組

public static void main(String[] args) {

		// 定義一個數組,保存五名學生的成績
		int[] scores = { 78, 93, 97, 84, 63 };

		//for循環打印
		for (int i = 0; i < scores.length; i++) {
			System.out.print(scores[i]+"  ");
		}
		System.out.println();
		//foreach打印
		//foreach是for語句的特殊簡化版本,在遍歷數組、集合時, foreach更簡單便捷。
		//for(元素類型  變量:遍歷對象){
		//執行的代碼
		//}
		for (int i : scores) {
			System.out.print(i+"  ");
		}
	}

執行結果
78 93 97 84 63
78 93 97 84 63

編程練習

package com.zhb;

public class Demo1 {
	public static void main(String[] args) {

		int[] nums = new int[] { 61, 23, 4, 74, 13, 148, 20 };

		int max = nums[0]; // 假定最大值為數組中的第一個元素
		int min = nums[0]; // 假定最小值為數組中的第一個元素
		double sum = 0;// 累加值
		double avg = 0;// 平均值

		for (int i = 0; i < nums.length; i++) { // 循環遍歷數組中的元素
			// 如果當前值大於max,則替換max的值

			if(nums[i]> max){
				max = nums[i];
			}

			// 如果當前值小於min,則替換min的值
			if(nums[i]< min){
				min = nums[i];
			}


			// 累加求和
			sum+=nums[i];

		}

		// 求平均值

		avg = sum/nums.length;
		System.out.println("數組中的最大值:" + max);
		System.out.println("數組中的最小值:" + min);
		System.out.println("數組中的平均值:" + avg);
	}

}

輸出結果
數組中的最大值:148
數組中的最小值:4
數組中的平均值:49.0

使用 Arrays 類操作 Java 中的數組

Arrays 類是 Java 中提供的一個工具類,在 java.util 包中。該類中包含了一些方法用來直接操作數組,比如可直接實現數組的排序、搜索等.

package com.zhb;

import java.util.Arrays;

public class Demo1 {
	public static void main(String[] args) {

		// 定義一個字符串數組
		String[] hobbys = { "sports", "game", "movie" };
        
		// 使用Arrays類的sort()方法對數組進行排序
		Arrays.sort(hobbys);	
		
		// 使用Arrays類的toString()方法將數組轉換為字符串並輸出
		System.out.println( Arrays.toString(hobbys) );
	}

}

執行結果
[game, movie, sports]

構建動態數組

其實,這里就是類似模擬實現ArrayList類的實現。這里只是簡化了部分。主要是代碼

首先我們先構建一個int類型的動態數組

  • 這里默認容量為10和ArrayList一致,這也告訴我們ArrayList默認容量為10,其中阿里規約提到,使用集合時,要指定集合初始值大小
/**
 * 動態int數組
 *
 * @author: curry
 * @Date: 2018/8/2
 */
public class Array {

    private int[] data;

    private int size;

    /**
     * 構造函數。傳入數組的容量capacity構造Array
     *
     * @param capacity
     */
    public Array(int capacity) {
        data = new int[capacity];
        size = 0;
    }

    /**
     * 無參構造函數,默認容量為10
     */
    public Array() {
        this(10);
    }

    /**
     * 獲取數組中的元素個數
     *
     * @return
     */
    public int getSize() {
        return size;
    }

    /**
     * 獲取數組容量
     *
     * @return
     */
    public int getCapacity() {
        return data.length;
    }

    /**
     * 返回數組是否為空
     *
     * @return
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 向數組最后添加元素
     *
     * @param e
     */
    public void addLast(int e) {
        add(size, e);
    }

    /**
     * 向數組最后增加一個元素
     *
     * @param e
     */
    public void addFirst(int e) {
        add(0, e);
    }

    /**
     * 向index位置增加元素e
     *
     * @param index
     * @param e
     */
    public void add(int index, int e) {
        // 判斷index 是否合法
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("index is error");
        }
        //判斷容量是否超出
        if (size == data.length) {
            throw new IllegalArgumentException("Array is full");
        }

        //將index后面的值進行后移
        for (int i = size - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }
        //賦值到index 位置
        data[index] = e;

        size++;

    }

    /**
     * 獲取index索引位置的值
     *
     * @param index
     * @return
     */
    public int get(int index) {
        // 判斷index 是否合法
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("index is error");
        }
        return data[index];
    }

    public void set(int index, int e) {
        // 判斷index 是否合法
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("index is error");
        }
        data[index] = e;
    }

    /**
     * 查找數組中的是否有元素
     *
     * @param e
     * @return
     */
    public boolean contains(int e) {

        for (int i = 0; i < size; i++) {
            if (data[i] == e) {
                return true;
            }
        }

        return false;

    }

    /**
     * 查找數組中元素e所在的索引
     *
     * @param e
     * @return
     */
    public int find(int e) {
        for (int i = 0; i < size; i++) {
            if (data[i] == e) {
                return i;
            }
        }

        return -1;
    }

    /**
     * 刪除索引為index的值
     *
     * @param index
     * @return
     */
    public int remove(int index) {


        // 判斷index 是否合法
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("index is error");
        }

        int ret = data[index];

        for (int i = index; i < size; i++) {
            data[i] = data[i + 1];
        }
        size--;
        return ret;
    }

    /**
     * 刪除第一個元素
     *
     * @return
     */
    public int removeFirst() {
        return remove(0);
    }

    /**
     * 刪除最后一個元素
     *
     * @return
     */
    public int removeLast() {
        return remove(size - 1);
    }

    /**
     * 刪除數組中的元素
     *
     * @param e
     */
    public void removeElement(int e) {
        int index = find(e);

        if (index != -1) {
            remove(index);
        }

    }

    @Override
    public String toString() {

        StringBuilder res = new StringBuilder();
        res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
        res.append("[");
        for (int i = 0; i < size; i++) {
            res.append(data[i]);
            if (i != size - 1) {
                res.append(", ");
            }
        }
        res.append("]");
        return res.toString();
    }


}

修改上面的代碼,加入泛型

  • 注意:這里增加了resize方法,用於擴容,因為底層還是數組實現的,所以當數組的長度不夠的時候,需要擴容,這里擴容為原先長度的2倍。ArrayList中為1.5倍
/**
 * 使用泛型
 *
 * @author: curry
 * @Date: 2018/8/2
 */
public class Array1<E> {

    private E[] data;

    private int size;

    /**
     * 構造函數。傳入數組的容量capacity構造Array
     *
     * @param capacity
     */
    public Array1(int capacity) {
        data = (E[]) new Object[capacity];
        size = 0;
    }

    /**
     * 無參構造函數,默認容量為10
     */
    public Array1() {
        this(10);
    }

    /**
     * 獲取數組中的元素個數
     *
     * @return
     */
    public int getSize() {
        return size;
    }

    /**
     * 獲取數組容量
     *
     * @return
     */
    public int getCapacity() {
        return data.length;
    }

    /**
     * 返回數組是否為空
     *
     * @return
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 向數組最后添加元素
     *
     * @param e
     */
    public void addLast(E e) {
        add(size, e);
    }

    /**
     * 向數組最后增加一個元素
     *
     * @param e
     */
    public void addFirst(E e) {
        add(0, e);
    }

    /**
     * 向index位置增加元素e
     *
     * @param index
     * @param e
     */
    public void add(int index, E e) {
        // 判斷index 是否合法
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("index is error");
        }
        //判斷容量是否超出
        if (size == data.length) {
            resize(2 * data.length);
        }

        //將index后面的值進行后移
        for (int i = size - 1; i >= index; i--) {
            data[i + 1] = data[i];
        }
        //賦值到index 位置
        data[index] = e;

        size++;

    }

    /**
     * 獲取index索引位置的值
     *
     * @param index
     * @return
     */
    public E get(int index) {
        // 判斷index 是否合法
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("index is error");
        }
        return data[index];
    }

    public void set(int index, E e) {
        // 判斷index 是否合法
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("index is error");
        }
        data[index] = e;
    }

    /**
     * 查找數組中的是否有元素
     *
     * @param e
     * @return
     */
    public boolean contains(E e) {

        for (int i = 0; i < size; i++) {
            if (data[i].equals(e)) {
                return true;
            }
        }

        return false;

    }

    /**
     * 查找數組中元素e所在的索引
     *
     * @param e
     * @return
     */
    public int find(E e) {
        for (int i = 0; i < size; i++) {
            if (data[i].equals(e)) {
                return i;
            }
        }

        return -1;
    }

    /**
     * 刪除索引為index的值
     *
     * @param index
     * @return
     */
    public E remove(int index) {


        // 判斷index 是否合法
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("index is error");
        }

        E ret = data[index];

        for (int i = index; i < size; i++) {
            data[i] = data[i + 1];
        }

        size--;
        data[size] = null;
        return ret;
    }

    /**
     * 刪除第一個元素
     *
     * @return
     */
    public E removeFirst() {
        return remove(0);
    }

    /**
     * 刪除最后一個元素
     *
     * @return
     */
    public E removeLast() {
        return remove(size - 1);
    }

    /**
     * 刪除數組中的元素
     *
     * @param e
     */
    public void removeElement(E e) {
        int index = find(e);

        if (index != -1) {
            remove(index);
        }

    }

    @Override
    public String toString() {

        StringBuilder res = new StringBuilder();
        res.append(String.format("Array: size = %d , capacity = %d\n", size, data.length));
        res.append("[");
        for (int i = 0; i < size; i++) {
            res.append(data[i]);
            if (i != size - 1) {
                res.append(", ");
            }
        }
        res.append("]");
        return res.toString();
    }

    /**
     * 擴容
     *
     * @param newCapacity
     */
    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];

        for (int i = 0; i < data.length; i++) {
            newData[i] = data[i];
        }

        data = newData;
    }


}

其實,這里寫的動態數組,也是在實現一個簡單的ArrayList類。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM