Generic collection in java
A generic collection in Java refers to a collection (such as List, Set, Queue, Map, etc.) that is parameterized with a type parameter. Generics in Java allow classes and methods to operate on objects of various types while providing compile-time type safety.

Table of Contents
Here’s a breakdown
1. Explanation
- Generic collections allow you to define a collection that can store elements of a specific type, known as the type parameter. This enables you to create reusable and type-safe data structures.
- By using generics, you can ensure type safety at compile time, reducing the likelihood of runtime errors related to type mismatches.
2. Usage
- Generic are commonly used when you want to create data structures that can work with different types of objects while maintaining type safety.
- They provide flexibility and reusability, allowing you to write generic algorithms that can operate on collections of different types.
Example
Example
java
import java.util.ArrayList;
import java.util.List;
public class GenericCollectionExample {
public static void main(String[] args) {
// Creating a generic collection (ArrayList) of strings
List<String> stringList = new ArrayList<>();
// Adding elements to the list
stringList.add("Hello");
stringList.add("World");
// Accessing elements from the list
for (String str : stringList) {
System.out.println(str);
}
// Creating a generic collection (ArrayList) of integers
List<Integer> integerList = new ArrayList<>();
// Adding elements to the list
integerList.add(10);
integerList.add(20);
// Accessing elements from the list
for (Integer num : integerList) {
System.out.println(num);
}
}
}
G C Example
In this example, we create two generic collections using the ArrayList class: one to store strings and another to store integers. We specify the type parameter within angle brackets ( and ) when declaring the collections. This ensures that only strings can be added to stringList and only integers can be added to integerList. Using generics enhances code readability and provides type safety, allowing the compiler to catch type-related errors at compile time.