ArrayLists and Collection Framework
Fixed-Size Arrays
- Arrays have a fixed length that cannot be changed after creation.
- Memory is allocated during creation, before elements are added.
- Adding extra elements after creation is not possible.
- Resizing requires creating a new array and copying elements.
ArrayList Class
- ArrayList is a built-in class in Java Collections Framework.
- Supports dynamic arrays that can increase/decrease in size.
- Elements can be inserted/deleted at specific positions.
- ArrayList has many methods to manipulate stored objects.
- Without Generics, ArrayList can hold any type of object.
Collection Framework
- A framework offers a ready-made architecture with classes and interfaces.
- A collection represents a group of objects.
- All classes/interfaces are in the
java.utli package.
How to use ArrayList
- Step 01: Import ArrayList class
- Step 02: Create/Declare an object from ArrayList class
- Step 03: Add elements (objects) to the created arraylist object
- Step 04: Modifying Elements
- Step 05: Accessing Elements
- Step 06: Removing Elements
- Step 07: Retrieve Size & Emptiness
- Step 08: Iteration - Classic For Loop
- Step 09: Iteration - Enhanced For Loop
Generics
- Generics mean parameterized types.
- Allows types (Integer, String, etc.) to be parameters for methods, classes, & interfaces.
- Before Generics, Java used Object to store any type of data (lacked type safety).
- Generics add type safety by restricting the types of values an ArrayList can hold.
Limitations of Generics
- Generics work only with Reference Types, not primitive data types (int, char).
- Compile-time errors occur when using primitive types directly.
- Use wrapper classes to encapsulate primitive types.
Wrapper Classes
- Wrapper classes convert primitive datatypes into objects and vice versa.
- Each primitive datatype has a corresponding wrapper class in the
java.lang package.