JAVA數據結構之數組詳細教程

本文整理了java數據結構的數組操作。希望對剛入門數據結構的同志們有幫助。
java數組非常簡單。只要有JAVA語言基礎就可以看這篇博文。大家不要害怕。。。非常簡單。。
整理博客真的很花費時間,如果對大家有幫助,麻煩點贊評論,讓我有動力繼續更新下去,謝謝大家。

數組基礎

數組的結構如下:
在這裏插入圖片描述我們在存數據的時候,存在數組裏面,以索引來讀取數據。可以通過數組名【索引】的形式訪問。每一個格子都存放一個數據。
創建一個索引的代碼:

/**
 * Created by hongyonghan
 */
public class Main {
    public static void main(String[]args){

        //方法一:聲明一個數組,並給定數組長度
        int [] arr=new int[10];
        for (int i=0;i<arr.length;i++)
        {
            //給arr數組賦值賦值
            arr[i]=i;
        }

        //方法二:直接給數組賦初值
        int[] scores=new int[]{100,99,66};
        for (int i=0;i<scores.length;i++)
        {
            System.out.println(scores[i]);
        }
        //使用foreach的形式遍歷數組
        for (int score:scores)
        {
            System.out.println(score);
        }

        //更改數組的值
        scores[0]=98;
        for (int score:scores)
        {
            System.out.println(score);
        }
    }
}

數組的優點和不足:
在這裏插入圖片描述
如果使用上面身份證號作爲一個索引的話,就需要開闢這麼大的數組空間,對計算機來說開闢這麼大空間是不現實的。
在這裏插入圖片描述
java數組本身沒有提供添加、刪除數組元素這些功能,所以需要我們自己二次封裝我們自己的數組。
在這裏插入圖片描述
上面的size是我們數組中有實際值元素的個數,而capacity是數組的容量。
下面是創建一個數組及初始化。

private Array(int capacity)
    {
        data=new int[capacity];
        size=0;
    }
    //無參數的構造函數
    public Array() {
        //如果用戶不傳入capacity的話,就默認構建一個長度是10的數組。
        this(10);
    }

    //獲取數組中的元素個數
    public int getSize()
    {
        return size;
    }
    //獲取數組的容量
    public int getCapapcity()
    {
        return data.length;
    }

    //獲取數組是否爲空
    public boolean isEmpty()
    {
        return size==0;
    }

向數組中添加元素

在這裏插入圖片描述
向數組末添加元素就是給定一個值,然後就可以直接添加進去。這裏解釋一下:這裏的size值在最開始創建數組的時候,就是指在數組長度的位置上,也就是0那個位置。那麼添加的話,也是添加在0那個位置。以後我們每添加一個元素除了給那個位置添加一個元素以外,還有給size的位置加一,目的是讓這個size指在前面的位置上。

    //向所有元素後添加一個新元素
    public void addLast(int e)
    {
        if (size==data.length)
        {throw new IllegalArgumentException("failed;array is full");}
        //給size位置賦值。
        data[size]=e;
        //更新size的位置
        size++;
   }

向數組中指定位置添加元素

做法就是將指定位置以後的元素都往後挪動一個位置。下面是添加過程:
下面第一個圖是一開始數據的位置,我們將77插入到索引位置爲1的位置。那麼將索引是1之後的所有元素後移,然後將77放在索引是1的位置的地方。
後移的過程是:將前面的值賦值給後面的值。比如這裏將100賦值在size指向的位置,將99賦值到100位置處。
在這裏插入圖片描述
在這裏插入圖片描述
然後將元素放在這個位置,並且size也要加加。
在這裏插入圖片描述

 //在第index個位置插入元素e
    public void add(int index,int e)
    {
        if (size==data.length)
        {throw new IllegalArgumentException("failed;array is full");}
        if(index <0 || index > size )
        {
            throw new IllegalArgumentException("failed;index  >= 0 and  index <=size");
        }
        for (int i = size-1;i >= index; i--)
        {
            data[i+1]=data[i];
        }
        data[index]=e;
        size++;
    }

    //在所有元素前添加一個新元素添加元素
    public void addFirst(int e)
    {
        add(0,e);
    }
   //根據index索引位置獲取元素
    public int get(int index)
    {
        if (index <0 || index >= size)
        {
            throw new IllegalArgumentException("failes,index is illegal");
        }
        return data[index];
    }
//修改index處位置爲e
    public void set(int index,int e)
    {        if (index <0 || index >= size)
    {
        throw new IllegalArgumentException("failes,index is illegal");
    }
        data[index]=e;
    }
 //查看元素中是否包含元素e
    public boolean contains(int e)
    {
        for (int i=0;i<size;i++)
        {
            if (data[i]==e)
            {
                return true;
            }
        }
        return false;
    }
 //查找數組中元素e所在的索引,如果不存在元素e,則返回-1
    public int find(int e)
    {
        for (int i=0;i<size;i++)
        {
            if (data[i]==e)
            {
                return i;
            }
        }
        return -1;
    }

從數組中刪除元素

數組中刪除元素就是將某個位置之後的全部值前移,覆蓋要刪除位置的元素,然後size減減。
在這裏插入圖片描述
size要進行減減。
在這裏插入圖片描述

   //從數組中刪除index位置的元素,返回刪除的元素
    public int remove(int index)
    {
        if (index <0 || index >= size)
        {
            throw new IllegalArgumentException("failes,index is illegal");
        }
        int ret=data[index];
        for (int i=index+1;i<size;i++)
        {
            data[i-1]=data[i];
        }
        size--;
        return ret;
    }
        //從數組中刪除第一個元素,返回刪除的元素
    public int removeFirst()
    {
        return remove(0);
    }
    //從數組中刪除最後一個元素,返回刪除元素。
    public int removeLast()
    {
        return remove(size-1);
    }
    //從數組中刪除元素e
    public boolean removeElement(int e)
    {
        int index=find(e);
        if (index != -1)
        {
            remove(index);
            return true;
        }
        return false;
    }

泛型

在這裏插入圖片描述

public class Array <E>{}

加了聲明成爲一個泛型數組,那麼這個E就是數組中存放元素的類型。可以是int,可以是string等等。
全部代碼如下:

/**
 * Created by hongyonghan on 2020/4/12.
 */
public class Array <E>{
    //定義數組
    private E[] data;
    //定義數組中元素的個數
    private int size;

    //capacity相當於是設定數組的大小


    public Array(int capacity)
    {
        data= (E[]) new Object[capacity];
        size=0;
    }
    //無參數的構造函數
    public Array() {
        //如果用戶不傳入capacity的話,就默認構建一個長度是10的數組。
        this(10);
    }

    //獲取數組中的元素個數
    public int getSize()
    {
        return size;
    }
    //獲取數組的容量
    public int getCapapcity()
    {
        return data.length;
    }

    //獲取數組是否爲空
    public boolean isEmpty()
    {
        return size==0;
    }

    //向所有元素後添加一個新元素
//    public void addLast(int e)
//    {
//        if (size==data.length)
//        {throw new IllegalArgumentException("failed;array is full");}
//        data[size]=e;
//        size++;
//        //複用add
////        size=getSize();
////       add(size,e);
//    }



    //在第index個位置插入元素e
    public void add(int index,E e)
    {

        if(index <0 || index > size )
        {
            throw new IllegalArgumentException("failed;index  >= 0 and  index <=size");
        }
        if (size==data.length)
        {
            //動態數組
            resize(2*data.length);
        }
        for (int i = size-1;i >= index; i--)
        {
            data[i+1]=data[i];
        }
        data[index]=e;
        size++;
    }
    public void  addLast(E e)
    {
        add(size,e);
    }

    //在所有元素前添加一個新元素添加元素
    public void addFirst(E e)
    {
        add(0,e);
    }

    //根據index索引位置獲取元素
    public E get(int index)
    {
        if (index <0 || index >= size)
        {
            throw new IllegalArgumentException("failes,index is illegal");
        }
        return data[index];
    }
    //修改index處位置爲e
    public void set(int index,E e)
    {        if (index <0 || index >= size)
    {
        throw new IllegalArgumentException("failes,index is illegal");
    }
        data[index]=e;
    }

    //查看元素中是否包含元素e
    public boolean contains(E e)
    {
        for (int i=0;i<size;i++)
        {
            if (data[i].equals(e))
            {
                return true;
            }
        }
        return false;
    }

    //查找數組中元素e所在的索引,如果不存在元素e,則返回-1
    public int  find(E e)
    {
        for (int i=0;i<size;i++)
        {
            if (data[i].equals(e))
            {
                return i;
            }
        }
        return -1;
    }

    //從數組中刪除index位置的元素,返回刪除的元素
    public E remove(int index)
    {
        if (index <0 || index >= size)
        {
            throw new IllegalArgumentException("failes,index is illegal");
        }
        E ret=data[index];
        for (int i=index+1;i<size;i++)
        {
            data[i-1]=data[i];
        }
        size--;
        data[size]=null;//這句話不是必須的,因爲用戶是無法訪問到的。
        //減小容量
        if(size == data.length/4 && data.length /2 !=0 )
        {
            resize(data.length/2);
        }
        return ret;
    }
        //從數組中刪除第一個元素,返回刪除的元素
    public E removeFirst()
    {
        return remove(0);
    }
    //從數組中刪除最後一個元素,返回刪除元素。
    public E removeLast()
    {
        return remove(size-1);
    }
    //從數組中刪除元素e
    public boolean removeElement(E e)
    {
        int index=find(e);
        if (index != -1)
        {
            remove(index);
            return true;
        }
        return false;
    }

    //可以做findALL和removeAll函數




    @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();
    }

泛型就是用來處理數組中元素類型不同的問題的,使用泛型可以讓我們自定義數據類型。如下是自定義的數據類型對象:

/**
 * Created by hongyonghan
 */
public class Student {
    private String name;
    private int score;

    public Student() {
    }

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    @Override
    public String toString() {
        return String.format("Student(name:%s, score: %d)",name,score);
    }

    public static void main(String[]args){

        Array<Student> array=new Array<>();
        array.addLast(new Student("Alice",100));
        array.addLast(new Student("Bob",66));
        array.addLast(new Student("Hahan",88));
        System.out.println(array);
    }

}

動態數組

數組原數據:
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述


    //在第index個位置插入元素e
    public void add(int index,E e)
    {

        if(index <0 || index > size )
        {
            throw new IllegalArgumentException("failed;index  >= 0 and  index <=size");
        }
        if (size==data.length)
        {
            //動態數組添加
            resize(2*data.length);
        }
        for (int i = size-1;i >= index; i--)
        {
            data[i+1]=data[i];
        }
        data[index]=e;
        size++;
    }

   private void resize(int newCapacity)
    {
        //新建一個泛型數組,將之前的數組複製到新的數組當中。
        E[] newData= (E[]) new Object[newCapacity];
        for (int i=0;i<size;i++)
        {
            newData[i]=data[i];
        }
        data=newData;

    }

}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章