網站首頁 編程語言 正文
假設有一個規定長度的數組,如何擴容呢?最容易想到的是通過如下方式擴容:
class Program
{
static void Main(string[] args)
{
int[] arrs = new[] {1, 2, 3, 4, 5};
arrs[5] = 6;
}
}
報錯:未處理IndexOutOfRanageException,索引超出了數組界限。
創建一個擴容的臨時數組,然后賦值給原數組,使用循環遍歷方式
static void Main(string[] args)
{
int[] arrs = new[] {1, 2, 3, 4, 5};
int[] temp = new int[arrs.Length + 1];
//遍歷arrs數組,把該數組的元素全部賦值給temp數組
for (int i = 0; i < arrs.Length; i++)
{
temp[i] = arrs[i];
}
//把臨時數組賦值給原數組,這時原數組已經擴容
arrs = temp;
//給擴容后原數組的最后一個位置賦值
arrs[arrs.Length - 1] = 6;
foreach (var item in arrs)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
創建一個擴容的臨時數組,然后賦值給原數組,使用Array的靜態方法
像這種平常的數組間的拷貝,Array類肯定為我們準備了靜態方法:Array.Copy()。
static void Main(string[] args)
{
int[] arrs = new[] {1, 2, 3, 4, 5};
int[] temp = new int[arrs.Length + 1];
Array.Copy(arrs, temp, arrs.Length);
//把臨時數組賦值給原數組,這時原數組已經擴容
arrs = temp;
//給擴容后原數組的最后一個位置賦值
arrs[arrs.Length - 1] = 6;
foreach (var item in arrs)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
使用Array的靜態方法擴容
但是,拷貝來拷貝去顯得比較繁瑣,我們也可以使用Array.Resize()方法給數組擴容。
static void Main(string[] args)
{
int[] arrs = new[] {1, 2, 3, 4, 5};
Array.Resize(ref arrs, arrs.Length + 1);
//給擴容后原數組的最后一個位置賦值
arrs[arrs.Length - 1] = 6;
foreach (var item in arrs)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
總結:數組擴容優先考慮使用Array的靜態方法Resize,其次考慮把一個擴容的、臨時的數組賦值給原數組。
原文鏈接:https://www.cnblogs.com/darrenji/p/3978150.html
相關推薦
- 2022-06-02 C#生成帶注釋的dll并引用實現_C#教程
- 2022-06-16 Go項目編寫Makefile規則文件概述_Golang
- 2022-06-17 Ruby信號處理詳解_ruby專題
- 2022-09-09 python中對開區間和閉區間的理解_python
- 2022-12-29 react中將html字符串渲染到頁面的實現方式_React
- 2022-07-16 MultipartFile與base64互轉
- 2022-07-16 構建npm配置包
- 2022-04-17 Security前后端分離自定義登錄詳解
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支