search
HomeBackend DevelopmentC#.Net TutorialLearn more about the differences between arrays, Lists, and ArrayLists

Some knowledge points may have been used in daily life, but in actual development we may only know them and not know why, so regular summaries will be of great help to our improvement and progress. The following article will introduce to you the differences between arrays, Lists and ArrayLists. I hope it will be helpful to you.

Learn more about the differences between arrays, Lists, and ArrayLists

The difference between array, List and ArrayList

Arrays are stored continuously in memory , so its indexing speed is very fast, and assigning and modifying elements is also very simple, such as:

string[] s=new string[3];
//赋值
 s[0]="a"; s[1]="b"; s[2]="c";
//修改
 s[1]="b1";

But arrays also have some shortcomings. For example, it is very troublesome to insert data between two data in an array. When declaring an array, we must also specify the length of the array. If the length of the array is too long, it will cause a waste of memory. If the length of the array is too short, it will cause Data overflow error. This becomes very troublesome if we don't know the length of the array when declaring it. C# first provided the ArrayList object to overcome these shortcomings.

ArrayList is a special class provided by the .Net Framework for data storage and retrieval. It is part of the namespace System.Collections. Its size dynamically expands and contracts according to the data stored in it. Therefore, we do not need to specify its length when declaring the ArrayList object. ArrayList inherits the IList interface, so it can easily add, insert and remove data. For example:

ArrayList list = new ArrayList();
//新增数据
 list.Add("abc"); list.Add(123);
//修改数据
 list[2] = 345;
//移除数据
 list.RemoveAt(0);
//插入数据 
list.Insert(0, "hello world");

From the above example, ArrayList seems to solve all the shortcomings in the array, then it should It's perfect. Why does List appear again after C# 2.0?

In the list, we not only inserted the string "abc", but also inserted the number 123. In this way, inserting different types of data into ArrayList is allowed. Because ArrayList will treat all data inserted into it as object type. In this way, when we use the data in the ArrayList to deal with the problem, a type mismatch error is likely to be reported, which means that the ArrayList is not type safe. Even if we ensure that we are careful when inserting data and insert the same type of data, we still need to convert them into the corresponding original types for processing when using them. This involves boxing and unboxing operations, which will cause great performance losses.

The concept of boxing and unboxing: To put it simply: Boxing: It is to pack value type data into an instance of a reference type, such as assigning the value 123 of the int type to Object object o

int i=123; object o=(object)i;

Unboxing: It is to extract the value type from the reference data. For example, assign the value of object object o to an int type variable i

object o=123; int i=(int)o;

The process of boxing and unboxing is It's very performance-intensive.

It is precisely because ArrayList has the disadvantages of unsafe types and boxing and unboxing that the concept of generics appeared after C# 2.0. The List class is the generic equivalent of the ArrayList class. Most of its usage is similar to ArrayList, because the List class also inherits the IList interface. The most critical difference is that when declaring the List collection, we also need to declare the object type of the data in the List collection. For example:

List<int> list = new List<int>();
//新增数据
 list.Add(123);
//修改数据 
list[0] = 345;
//移除数据
list.RemoveAt(0);</int></int>


In the above example, if we insert the string character "hello world" into the List collection, the IDE will report an error and fail to compile. This avoids the type safety issues and performance issues of boxing and unboxing mentioned earlier.

At the same time, List cannot be constructed, but you can create a reference to List as above, and ListArray can be constructed.

List list;     //正确   list=null; 
List list=new List();    //   是错误的用法

List list = new ArrayList(); This sentence creates an ArrayList object and traces it back to the List. At this time it is a List object. Some ArrayList has properties and methods that List does not, so it can no longer be used. ArrayList list=new ArrayList(); creates an object and retains all the properties of ArrayList.

Benefits of List Generics:

The generics feature shifts the task of type safety from you to the compiler by allowing you to specify the specific types that a generic class or method operates on. There is no need to write code to detect whether the data type is correct because the correct data type is enforced at compile time. Reduces the need for type casts and the possibility of runtime errors. Generics provide type safety without the overhead of multiple implementations.

This article comes from the C#.Net Tutorial column, welcome to learn!

The above is the detailed content of Learn more about the differences between arrays, Lists, and ArrayLists. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:cnblogs. If there is any infringement, please contact admin@php.cn delete
The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing C# .NET Applications: Unit, Integration, and End-to-End TestingTesting C# .NET Applications: Unit, Integration, and End-to-End TestingApr 09, 2025 am 12:04 AM

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Advanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewAdvanced C# .NET Tutorial: Ace Your Next Senior Developer InterviewApr 08, 2025 am 12:06 AM

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft