Arrays and Collections in Java
Arrays in Java
Definition: Arrays are a fixed-size, homogeneous data structure in Java, meaning they store
elements of the same data type.
Key Features:
- Fixed size: Once defined, the size of an array cannot change.
- Zero-based index: Array indexing starts at 0.
- Homogeneous elements: Only elements of the same type can be stored.
Declaration:
int[] numbers = new int[5]; // Declares an array of integers with size 5
int[] numbers = {1, 2, 3, 4, 5}; // Declaration and initialization
Accessing Elements: Using index, e.g., numbers[0] gives the first element.
Common Operations:
- Iteration: Using for loop or enhanced for-each.
- Sorting: Using Arrays.sort(array) for sorting.
- Copying: Using Arrays.copyOf() for duplicating arrays.
Collections in Java
Definition: Collections in Java are flexible data structures that can store a dynamic number of
elements.
Key Features:
- Can grow or shrink in size dynamically.
- Offers a variety of implementations (List, Set, Map).
- Supports various operations like sorting, searching, and modifying.
Hierarchy:
- List: Ordered collection (e.g., ArrayList, LinkedList).
- Set: Unordered collection with unique elements (e.g., HashSet, TreeSet).
- Map: Key-value pairs (e.g., HashMap, TreeMap).
Common Operations:
- Add, Remove, and Retrieve: add(), remove(), get().
- Iteration: Using Iterator, for-each, or streams.
- Sorting: Collections like List can be sorted using Collections.sort().