Java Concepts: Arrays and Collections
1. Array and Collection:
Array:
- Fixed in size and homogeneous (stores elements of the same data type).
- Provides less flexibility in terms of operations.
- Example: int[] arr = new int[10];
Collection:
- Can grow dynamically and store heterogeneous elements.
- Part of the [Link] package, offering a wide range of data structures like List, Set, and Map.
- Example: ArrayList<Integer> list = new ArrayList<>();
2. ArrayList and LinkedList:
ArrayList:
- Implements a resizable array structure.
- Provides faster access time (O(1)) for elements.
- Slower for insertions and deletions as it may require shifting elements.
LinkedList:
- Implements a doubly linked list.
- Faster for insertions and deletions (O(1)) but slower for access (O(n)).
- Uses more memory due to storage of pointers.
3. List and Set:
List:
- Ordered collection that allows duplicate elements.
- Examples: ArrayList, LinkedList.
Set:
- Unordered collection that does not allow duplicate elements.
- Examples: HashSet, TreeSet.
4. Collection and Collections:
Collection:
- Interface in the [Link] package that is the root of the collection framework.
- Example: List, Set, Queue.
Collections:
- Utility class in [Link] package that provides static methods for operations on collections.
- Example: [Link](), [Link]().
5. Comparable and Comparator:
Comparable:
- Interface that defines a natural ordering for objects.
- Method: int compareTo(Object obj).
- Example: Implemented by String and Wrapper classes.
Comparator:
- Interface that defines custom ordering for objects.
- Method: int compare(Object obj1, Object obj2).
- Example: Used for multiple sorting criteria.