It stores a collection of similar data types.
The values are stored based on an index, starting from 0 to n-1.
Syntax: int num[] = new int[5]; Advantages of array:
- In a single variable we can store multiple values.
Disadvantages of array:
- Supports only similar data types.
- Fixed size.
- High memory wastage.
To overcome these, we go for collections.
java.util package (parent of List, Set, Map).java.util with static methods (like sort(), reverse(), etc.).It has 3 major types:
In Java, we can convert an array to a list in multiple ways:
Example:
Integer[] arr = {1, 2, 4, 5, 6};
List<Integer> list1 = Arrays.asList(arr); // Fixed-size
List<Integer> list2 = new ArrayList<>(Arrays.asList(arr)); // Modifiable retainAll() → Keeps only common elements.removeAll() → Removes common elements.add() → Inserts a new element at the index.set() → Replaces existing element at the index.Use for-each with entrySet():
for (Map.Entry<K, V> entry : map.entrySet()) { System.out.println(entry.getKey() + " = " + entry.getValue()); } Generics provide type safety and allow only similar data types.
Avoids typecasting at runtime.
Example: List<String> list = new ArrayList<>();
Referring a child class object with a parent class reference.
Example: List list = new ArrayList();
Converting parent reference back to child type.
Example: ArrayList list = (ArrayList) parentRef;
Type Casting is the process of converting one data type into another.
Signup