1
Feature |
Array |
ArrayList |
Type Safety |
Strongly typed |
Weakly typed (stores object ) |
Resizable |
? Fixed size |
? Automatically resizes |
Performance |
Faster (no boxing/unboxing) |
Slower (boxing/unboxing for value types) |
Generics Support |
? (Use T[] ) |
? (Use List<T> instead) |
Usage Recommendation |
Use for fixed-size, typed data |
Use List<T> instead of ArrayList |
Conceptual Differences
?? 1. Array
2. ArrayList
-
Part of System.Collections (non-generic).
-
Stores elements as object, allowing mixed types (not recommended).
-
Example:
ArrayList list = new ArrayList();
list.Add(1); // boxed int
list.Add("hello"); // string
Drawbacks:
-
Boxing/unboxing overhead with value types.
-
No compile-time type checking.
Example Comparison
// Array (strongly typed)
int[] ages = new int[2];
ages[0] = 25;
ages[1] = 30;
// ArrayList (weakly typed)
ArrayList data = new ArrayList();
data.Add(25); // boxed
data.Add("John"); // allowed, but dangerous
int age = (int)data[0]; // requires casting
Should You Use ArrayList
?
No — use List<T>
instead (from System.Collections.Generic
).
List<int> list = new List<int>();
list.Add(10); // no boxing
int num = list[0]; // no casting needed
In Summary:
Use Case |
Recommended Type |
Fixed-size, performance-critical |
Array |
Dynamic, type-safe collection |
List<T> |
Legacy non-generic collections |
ArrayList (not recommended) |
