JavaDS —— 順序表ArrayList

順序表

順序表是用一段物理地址連續的存儲單元依次存儲數據元素的線性結構,一般情況下采用數組存儲。在數組上完成數據的增刪查改。在物理和邏輯上都是連續的。

模擬實現

下面是我們要自己模擬實現的方法:

在這里插入圖片描述

首先我們要創建一個順序表,順序表包含一個數組,一個由于計數的計數器,還有一個默認的初始容量,我這里定義初始容量為5,比較好判斷擴容是否成功。這里以整型數組為例:

    private int[] array;private int usedSize;//目前數據總數private static final int DEFAULT_CAPACITY = 5;//默認容量

默認構造方法

這里我們直接在構造方法里給數組進行初始化:

    public MyArrayList() {array = new int[DEFAULT_CAPACITY];}

尾插

尾插是指直接在所有數據的后面插入新數據,這里我們要注意數組容量是否已滿,所以我們先寫一個isFull方法判斷數組是否容量已滿:

    private boolean isFull() {if(usedSize == array.length) {return true;}return false;}

這個方法設置成private是因為這個方法只是給本類的方法提供的,不需要對外公開。


如果數組已滿,那么我們就需要擴容,這里我擴容2倍:

    private void grow() {array = Arrays.copyOf(array,array.length * 2);}

現在來寫尾插代碼:

    public void add(int data) {//判滿if(isFull()) {grow();}//插入數據array[usedSize++] = data;}

pos位置插入數據

首先我們要先檢查pos位置是否合法,如果不合法的話就不用進行插入操作,直接拋出異常,我們先寫異常代碼:

public class PosException extends RuntimeException{public PosException(String message) {super(message);}
}

檢查pos位置是否合法:

    private void checkPosInAdd(int pos) throws PosException {if(pos < 0 || pos > usedSize) {throw new PosException("pos位置不合法");}}

現在寫插入代碼,首先判斷pos是否合法,然后判斷是否要擴容,最后我們進行插入操作即可,在插入代碼中,我們使用try-catch來處理異常。

    public void add(int pos,int data) {try{checkPosInAdd(pos);//檢查位置是否合法if(isFull()) {    //判滿grow();}//移動數據for (int i = usedSize; i >= pos ; i--) {array[i+1] = array[i];}//插入數據array[pos] = data;usedSize++;}catch (PosException e) {System.out.println("pos位置不合法!");e.printStackTrace();}}

contains

是否包含某個元素,使用布爾值進行返回,這里直接遍歷數組查找即可。

    public boolean contains(int toFind) {for (int i = 0; i < usedSize; i++) {if(array[i] == toFind){return true;}}return false;}

indexOf

查找某個元素的下標,找到則返回該元素的下標,沒有找到則返回 -1

    public int indexOf(int toFind) {for (int i = 0; i < usedSize; i++) {if(array[i] == toFind) {return i;}}return -1;}

get

找到pos位置的元素,這里要注意先判斷pos是否合法,但是這里的檢查pos和上面我們寫過的checkPosInAdd是不一樣的,這里的pos必須是有元素的下標范圍,也就是不包含usedSize這個下標,因為這個是沒有有效數據的,是待插入的空位,所以我們要再寫一個檢查pos方法:

    private void checkPosInFind(int pos) throws PosException {if(pos < 0 || pos >= usedSize) {throw new PosException("pos位置不合法");}}

    public int get(int pos) {try{checkPosInFind(pos);return array[pos];}catch (PosException e) {System.out.println("pos位置不合法!");e.printStackTrace();}return -1;}

set

更新pos位置的數據,還是要判斷pos位置是否合法,這里使用發判斷方法應該為checkPosInFind

    public void set(int pos, int data) {try{checkPosInFind(pos);array[pos] = data;}catch (PosException e) {System.out.println("pos位置不合法!");e.printStackTrace();}}

remove

刪除第一次出現的關鍵字key

    public void remove(int key) {for (int i = 0; i < usedSize; i++) {if(array[i] == key) {for (int j = i; j < usedSize - 1; j++) {array[j] = array[j+1];}usedSize--;return;}}}

size

獲取順序表的長度,這里直接返回usedSize即可

    public int size() {return usedSize;}

display

打印順序表,該方法是便于測試,真正的順序表并沒有這個方法

    public void display() {for (int i = 0; i < usedSize; i++) {System.out.print(array[i] + " ");}System.out.println();}

clear

清空順序表,直接將usedSize賦值為0即可,下次使用的時候,會直接覆蓋之前的數據的。

    public void clear() {usedSize = 0;}

完整代碼

import java.util.Arrays;public class MyArrayList {private int[] array;private int usedSize;//目前數據總數private static final int DEFAULT_CAPACITY = 5;//默認容量public MyArrayList() {array = new int[DEFAULT_CAPACITY];}/*判滿,滿則返回true,否則返回false*/private boolean isFull() {if(usedSize == array.length) {return true;}return false;}//擴容 2倍擴容private void grow() {array = Arrays.copyOf(array,array.length * 2);}//尾插public void add(int data) {//判滿if(isFull()) {grow();}//插入數據array[usedSize++] = data;}//判斷pos是否合法/*不合法則拋出異常增加方法*/private void checkPosInAdd(int pos) throws PosException {if(pos < 0 || pos > usedSize) {throw new PosException("pos位置不合法");}}//指定pos位置插入數據public void add(int pos,int data) {try{checkPosInAdd(pos);//檢查位置是否合法if(isFull()) {    //判滿grow();}//移動數據for (int i = usedSize; i >= pos ; i--) {array[i+1] = array[i];}//插入數據array[pos] = data;usedSize++;}catch (PosException e) {System.out.println("pos位置不合法!");e.printStackTrace();}}//是否包含某個元素public boolean contains(int toFind) {for (int i = 0; i < usedSize; i++) {if(array[i] == toFind){return true;}}return false;}//查找某個元素的下標public int indexOf(int toFind) {for (int i = 0; i < usedSize; i++) {if(array[i] == toFind) {return i;}}return -1;}//判斷pos是否合法/*查找方法不合法則拋出異常*/private void checkPosInFind(int pos) throws PosException {if(pos < 0 || pos >= usedSize) {throw new PosException("pos位置不合法");}}//獲取pos位置的元素public int get(int pos) {try{checkPosInFind(pos);return array[pos];}catch (PosException e) {System.out.println("pos位置不合法!");e.printStackTrace();}return -1;}//更新pos位置的數據public void set(int pos, int data) {try{checkPosInFind(pos);array[pos] = data;}catch (PosException e) {System.out.println("pos位置不合法!");e.printStackTrace();}}//刪除第一次出現的關鍵字keypublic void remove(int key) {for (int i = 0; i < usedSize; i++) {if(array[i] == key) {for (int j = i; j < usedSize - 1; j++) {array[j] = array[j+1];}usedSize--;return;}}}//獲取順序表的長度public int size() {return usedSize;}//打印順序表,該方法是便于測試,真正的順序表并沒有這個方法public void display() {for (int i = 0; i < usedSize; i++) {System.out.print(array[i] + " ");}System.out.println();}//清空順序表public void clear() {usedSize = 0;}
}

ArrayList 的使用

Java已經封裝好順序表供我們使用,就是ArrayList,現在我們來列舉其中的常用的方法。

方法解釋
boolean add(E e)尾插 e
void add(int index, E element)將 e 插入到 index 位置
boolean addAll(Collection<? extends E> c)尾插 c 中的元素
E remove(int index)刪除index位置元素
boolean remove(Object o)刪除遇到的第一個o
E get(int index)獲取下標 index 位置元素
E set(int index, E element)將下標 index 元素設置為 element
void clear()清空
boolean contains(Object o)判斷 o 是否在線性表中
int indexOf(Object o)返回第一個 o 所在下標
int lastIndexOf(Object o)返回最后一個 o 的下標

更多詳細的方法可自行查閱官方文檔

上面很多方法是我們自己模擬實現過的,這里就不一一舉例演示。

ArrayList 的成員方法

在這里插入圖片描述

ArrayList 構造方法

一共提供了三個構造方法:

方法解釋
ArrayList()無參構造
ArrayList(Collection<? extends E> c)利用其他 Colletion 構建 ArrayList
ArrayList(int initialCapacity)指定順序表初始容量

ArrayList(int initialCapacity)指定順序表初始容量看一下源碼還是很好理解的,初始容量大于零就開辟一塊連續的空間,等于零就給一個空數組,小于零則拋出異常。

在這里插入圖片描述

首先要知道下面的關系圖:
在這里插入圖片描述

從上圖我們可以得知ArrayList是包含Collection這個接口的,所以可以接收Colletion的參數,Colletion后面的<? extends E> 中的 ? 是通配符,后面的文章會提到。

在這里插入圖片描述


我們重點是看無參的構造方法:

在這里插入圖片描述

直接賦值一個空數組,大家來看一下下面的代碼,明明是空數組,但是為什么可以直接add而不會報錯呢?

    public static void main(String[] args) {ArrayList<Integer> list = new ArrayList<>();list.add(10);list.add(20);System.out.println(list);}

在這里插入圖片描述

我們點過去看看源碼是什么:

在這里插入圖片描述

在這里插入圖片描述

到了這里大家應該明白了,在使用add的時候,我們看到源碼里寫了當 s == 數組長度的時候,Java底層會幫我們自動擴容。

ArrayList 實例化

我們經常使用List或者ArrayList來接收順序表實例化的對象.

        List<Integer> list = new ArrayList<>();ArrayList<Integer> list2 = new ArrayList<>();

由于List是ArrayList的接口,所以可以接收,但是注意List是接口意味著不能進行實例化,使用List接收的參數只能使用List有點方法,由于ArrayList有很多接口,一定是拓展了很多東西的,如果List接口沒有包含的方法,使用List接收的參數不能調用其他方法,但是使用ArrayList接收的話,所有ArrayList實現的方法都是可以調用的,只要是公開訪問即可.

ArrayList 遍歷方法

ArrayList 可以使用三方方式遍歷:for循環+下標、foreach、使用迭代器,還可以直接打印里面的內容。

        int size = list.size();for (int i = 0; i < size; i++) {System.out.print(list.get(i) + " ");}System.out.println();

無論是Integer還是int接收元素,Java底層會幫我們自動拆箱的.

        for (int x: list) {System.out.print(x + " ");}System.out.println();for (Integer y: list) {System.out.print(y + " ");}System.out.println();
        ListIterator<Integer> it =  list.listIterator(list.size());while (it.hasPrevious()) {System.out.print(it.previous()+" ");}System.out.println();

Java的ArrayList的父類是重寫過toString方法的.

        System.out.println(list);

在這里插入圖片描述

實踐

楊輝三角

在這里插入圖片描述

在這里插入圖片描述

這里要注意 List<List< Integer>> ,這個意思表示外面的list的元素是list,里面的list的元素是Integer,例如下圖所示:類似二維數組~

在這里插入圖片描述

代碼:

class Solution {public List<List<Integer>> generate(int numRows) {List<List<Integer>> list = new ArrayList<>();List<Integer> list0 = new ArrayList<>();list0.add(1);list.add(list0);for(int i=1;i<numRows;i++) {List<Integer> list1 = new ArrayList<>();for(int j=0;j<=i;j++) {if(j==0 || j==i) {list1.add(1);} else {list1.add(list.get(i-1).get(j-1) + list.get(i-1).get(j));}}list.add(list1);}return list;}
}

洗牌功能實現

public class Card {private int number;private String cardColor;public Card(int number, String cardColor) {this.number = number;this.cardColor = cardColor;}@Overridepublic String toString() {return "Card{" +cardColor + '\'' +number +'}';}
}
import java.util.ArrayList;
import java.util.List;
import java.util.Random;public class PlayCard {private static final String[] cardColor = {"?","?","?","?"};//購買52張牌public List<Card> buyCards() {List<Card> list = new ArrayList<>();for (int i = 1; i <= 13; i++) {for (int j = 0; j < 4; j++) {Card card = new Card(i,cardColor[j]);list.add(card);}}return list;}//洗牌public void shuffle(List<Card> list) {Random random = new Random();int size = list.size();for (int i = 0; i < size; i++) {int index = random.nextInt(size);//生成 0 ~ i-1 的隨機數Card card = list.get(index);list.set(index,list.get(i));list.set(i,card);}}//發牌public List<List<Card>> deal(List<Card> cards) {List<List<Card>> list = new ArrayList<>();//創建三個人List<Card> list0 = new ArrayList<>();List<Card> list1 = new ArrayList<>();List<Card> list2 = new ArrayList<>();list.add(list0);list.add(list1);list.add(list2);int size = cards.size();int size2 = list.size();int count = 0;boolean flag = true;while(flag) {for (int j = 0; j < size2; j++) {list.get(j).add(cards.remove(0));count++;if(count == size){flag = false;break;}}}return list;}
}

這里要注意隨機數的建立,首先先實例化Ramdom對象,然后使用nextInt方法,nextInt(int bound),生成的隨機數范圍是0~bound-1.

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/42116.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/42116.shtml
英文地址,請注明出處:http://en.pswp.cn/web/42116.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

關于Mars3d的入門

關于Mars3d的入門 一. 創建地球&#xff0c;加載瓦片圖層二 矢量圖層2.1 常用矢量圖層2.1.1 GraphicLayer2.1.2 GeoJsonLayer 2.2 矢量圖層的點擊事件 三 矢量數據四 事件機制 一. 創建地球&#xff0c;加載瓦片圖層 // 1. 創建地球let map new mars3d.Map("mars3dContai…

基于openStreetMap的路徑規劃ROS功能包

文章目錄 概要OSM是什么主要特點主要組成部分使用場景如何獲取OSM常規參數配置笛卡爾坐標系原點經緯度設置編譯和運行如何規劃演示效果概要 由于https://github.com/MichalDobis/osm_planner存在一些使用問題,不是那么方便,我對其進行了一些修改,便于進行起點到終點進行路徑…

數據如何查詢

分組查詢 分組查詢&#xff08;Group By&#xff09;是在關系型數據庫中用來對數據進行分組并對每個組應用聚合函數的一種操作。這種查詢通常結合聚合函數&#xff08;如 COUNT、SUM、AVG、MAX、MIN 等&#xff09;使用&#xff0c;用于在查詢結果中生成匯總信息 特點(聚合)&am…

從零開始做題:My_lllp

題目 給出一張png圖片 解題 ┌──(holyeyes?kali2023)-[~/Misc/題目/zulu/My_lllp] └─$ python2 lsb.py extract my_lllp.png out.txt my_lllp [] Image size: 1080x1079 pixels. [] Written extracted data to out.txt. ┌──(holyeyes?kali2023)-[~/Misc/題目/zul…

python的線程池和進程池

Python 3.2 就已經引入了 concurrent.futures 模塊&#xff0c;提供了線程池&#xff08;ThreadPoolExecutor&#xff09;和進程池&#xff08;ProcessPoolExecutor&#xff09;&#xff0c;用于簡化并發編程的管理和調度。 ThreadPoolExecutor 在ThreadPoolExecutor 是 conc…

簡易Qt串口助手

界面顯示如下 關于串口類 初始化 設置串口號 設置波特率 打開串口 發送按鈕功能實現 接收數據顯示在控件中 關閉串口

使用 MFA 保護對企業應用程序的訪問

多因素身份驗證&#xff08;MFA&#xff09;是在授予用戶訪問特定資源的權限之前&#xff0c;使用多重身份驗證來驗證用戶身份的過程&#xff0c;僅使用單一因素&#xff08;傳統上是用戶名和密碼&#xff09;來保護資源&#xff0c;使它們容易受到破壞&#xff0c;添加其他身份…

springboot非物質文化遺產管理系統-計算機畢業設計源碼16087

目錄 摘要 1 緒論 1.1 選題背景與意義 1.2國內外研究現狀 1.3論文結構與章節安排 2系統分析 2.1 可行性分析 2.2 系統流程分析 2.2.1系統開發流程 2.2.2 用戶登錄流程 2.2.3 系統操作流程 2.2.4 添加信息流程 2.2.5 修改信息流程 2.2.6 刪除信息流程 2.3 系統功能…

前端開發過程中經常遇到的問題以及對應解決方法 (持續更新)

我的朋友已經工作了 3 年&#xff0c;他過去一直擔任前端工程師。 不幸的是&#xff0c;他被老板批評了&#xff0c;因為他在工作中犯了一個錯誤&#xff0c;這是一個非常簡單但容易忽視的問題&#xff0c;我想也是很多朋友容易忽視的一個問題。 今天我把它分享出來&#xff…

Linux三劍客(grep、awk和sed)操作及與管道結合使用

1. 總覽 grep、sed和awk被稱為Linux三劍客&#xff0c;是因為它們在文本處理和數據操作方面極其強大且常用。 Linux三劍客在文件處理中的作用&#xff1a; grep&#xff08;數據查找定位&#xff09;&#xff1a;文本搜索工具&#xff0c;在文件中搜索符合正則表達式的文本內容…

Redis原理-數據結構

Redis原理篇 1、原理篇-Redis數據結構 1.1 Redis數據結構-動態字符串 我們都知道Redis中保存的Key是字符串&#xff0c;value往往是字符串或者字符串的集合。可見字符串是Redis中最常用的一種數據結構。 不過Redis沒有直接使用C語言中的字符串&#xff0c;因為C語言字符串存…

【大模型LLM面試合集】大語言模型架構_attention

1.attention 1.Attention 1.1 講講對Attention的理解&#xff1f; Attention機制是一種在處理時序相關問題的時候常用的技術&#xff0c;主要用于處理序列數據。 核心思想是在處理序列數據時&#xff0c;網絡應該更關注輸入中的重要部分&#xff0c;而忽略不重要的部分&…

BJT的結構(晶體管電壓/電流+β+晶體管特性曲線/截止與飽和+直流負載線(Q點))+單片機數碼管基礎

2024-7-8&#xff0c;星期一&#xff0c;20:23&#xff0c;天氣&#xff1a;晴&#xff0c;心情&#xff1a;晴。今天沒有什么特殊的事情發生&#xff0c;周末休息了兩天&#xff0c;周一回來繼續學習啦&#xff0c;加油加油&#xff01;&#xff01;&#xff01; 今日完成模電…

視頻號矩陣管理系統:短視頻內容營銷的智能助手

隨著短視頻行業的蓬勃發展&#xff0c;視頻號矩陣管理系統應運而生&#xff0c;為內容創作者和品牌提供了一站式的短視頻管理和營銷解決方案。本文將深入探討視頻號矩陣管理系統的核心功能&#xff0c;以及它如何助力用戶在短視頻營銷領域取得成功。 視頻號矩陣管理系統概述 …

在PyTorch中使用TensorBoard

文章目錄 在PyTorch中使用TensorBoard1.安裝2.TensorBoard使用2.1創建SummaryWriter實例2.2利用add_scalar()記錄metrics2.3關閉Writer2.4啟動TensorBoard 3.本地連接服務器使用TensorBoard3.1方法一&#xff1a;使用SSH命令進行本地端口轉發3.2方法二&#xff1a;啟動TensorBo…

Python 全棧體系【三階】(二)

第一章 Django 五、模板 1. 概述 Django中的模板是指可以動態生成任何基于文本格式文件的技術&#xff08;如HTML、CSS等&#xff09;。 Django中內置了自己的模板系統&#xff0c;稱為DTL(Django Template Language), Django模板語言。 2. 配置 settings.py中關于模板的…

如何將資源前端通過 Docker 部署到遠程服務器

作為一個程序員&#xff0c;在開發過程中&#xff0c;經常會遇到項目部署的問題&#xff0c;在現在本就不穩定的大環境下&#xff0c;前端開發也需要掌握部署技能&#xff0c;來提高自己的生存力&#xff0c;今天就詳細說一下如何把一個前端資源放到遠程服務器上面通過docker部…

紫外線芯片殺菌燈問題

1.265nm深紫外光子能量是多少 504kj/mol 2.紫外光分解有害物質的原理是什么&#xff1f; 通過紫外光分子鍵打斷有害物質的分子鍵&#xff0c;使其分解成co2和H2o等無害物質 3.紫外光殺菌的原理是什么&#xff1f; 通過特定波長的紫外光照射&#xff0c;破壞和改變微生物的…

【網絡協議】PIM

PIM 1 基本概念 PIM&#xff08;Protocol Independent Multicast&#xff09;協議&#xff0c;即協議無關組播協議&#xff0c;是一種組播路由協議&#xff0c;其特點是不依賴于某一特定的單播路由協議&#xff0c;而是可以利用任意單播路由協議建立的單播路由表完成RPF&…

【Python】不小心卸載pip后(手動安裝pip的兩種方式)

文章目錄 方法一&#xff1a;使用get-pip.py腳本方法二&#xff1a;使用easy_install注意事項 不小心卸載pip后&#xff1a;手動安裝pip的兩種方式 在使用Python進行開發時&#xff0c;pip作為Python的包管理工具&#xff0c;是我們安裝和管理Python庫的重要工具。然而&#x…