Practical Generic Examples
1. Generic Swap Method
A utility method to swap elements of any type:
public class GenericUtility {
public <T> void swap(T[] array, int i, int j) {
T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3, 4, 5};
String[] stringArray = {"Hello", "World", "Java"};
GenericUtility utility = new GenericUtility();
utility.swap(intArray, 0, 1);
utility.swap(stringArray, 0, 1);
}
}
2. Generic Pair Class
A flexible generic class for storing two related values:
public class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
3. Generic Method for Finding Maximum
A generic method to find the maximum element in an array:
public class GenericMaxFinder {
public <T extends Comparable<T>> T findMax(T[] array) {
if (array == null || array.length == 0) {
return null;
}
T max = array[0];
for (T element : array) {
if (element.compareTo(max) > 0) {
max = element;
}
}
return max;
}
public static void main(String[] args) {
Integer[] intArray = {1, 5, 3, 7, 2};
String[] stringArray = {"apple", "banana", "cherry"};
GenericMaxFinder finder = new GenericMaxFinder();
System.out.println("Max Integer: " + finder.findMax(intArray));
System.out.println("Max String: " + finder.findMax(stringArray));
}
}
4. Generic Method for Type-Safe Collection Operations
public class CollectionOperations {
public <T> void printCollection(Collection<T> collection) {
for (T element : collection) {
System.out.println(element);
}
}
public <T> List<T> filterCollection(
Collection<T> collection,
Predicate<T> predicate
) {
return collection.stream()
.filter(predicate)
.collect(Collectors.toList());
}
}
Generic Method Patterns Comparison
Pattern |
Use Case |
Type Safety |
Flexibility |
Swap Method |
Element Exchange |
High |
Very High |
Pair Class |
Key-Value Storage |
Strong |
Adaptable |
Max Finder |
Comparative Operations |
Very Strong |
Specific |
Collection Operations |
Filtering/Processing |
Robust |
Extensible |
Generic Method Workflow
graph TD
A[Generic Method Definition] --> B[Type Parameter Specification]
B --> C[Method Implementation]
C --> D[Type-Safe Invocation]
D --> E[Runtime Execution]
Best Practices
- Use meaningful type parameter names
- Leverage bounded type parameters
- Minimize type casting
- Prefer generic methods over raw types
LabEx Learning Approach
At LabEx, we recommend practicing these patterns through incremental coding challenges to build practical generic programming skills.
- Generic methods have minimal runtime overhead
- Compile-time type checking ensures type safety
- Use generics to improve code readability and maintainability