Generic Collections
Generic Collections
Engineering
Course Code: E1UA307C Course Name:Java Programming
1
Faculty Name: Jitender Tanwar Programe Name: B.Tech
Generic Collections: Generic Classes and Methods
In object-oriented programming (OOP), generics allow you to write flexible,
reusable, and type-safe code. Generic collections are collections that can
store objects of any type, but the type is defined at the time of creation.
This allows collections to work with different types of data without
compromising type safety or needing to cast types explicitly.
1.Type Safety:
•Generics allow you to catch type errors at compile-time rather than at
runtime. Without generics, you might need to cast objects, which could
lead to ClassCastException errors at runtime.
2.Code Reusability:
•You can write more reusable code that works with different types without
duplicating logic.
3.Performance:
•Generics eliminate the need for casting and work with specific types,
leading to better performance compared to using raw types (non-generic).
import java.util.ArrayList;
public class GenericCollectionExample {
Example of a Generic public static void main(String[] args) {
Collection: // Create an ArrayList that holds Integer values
Java’s ArrayList The ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
ArrayList class in Java is numbers.add(20);
a part of the java.util numbers.add(30);
package and is a generic // Print the elements in the ArrayList
for (Integer number : numbers) {
collection that can store System.out.println(number); // Output: 10, 20, 30 }
elements of any type. // Create an ArrayList that holds String values
ArrayList<String> words = new ArrayList<>();
words.add("Apple");
words.add("Banana");
words.add("Cherry");
// Print the elements in the ArrayList
for (String word : words) {
System.out.println(word); // Output: Apple, Banana, Cherry
} }}
Thank you