Java Generics
java Generics with collection examples
Java Generics allow you to write type-safe code that can operate on a variety of types, while still providing compile-time type checking. This can be especially useful when working with collections, as it allows you to specify the type of objects that a collection can hold, which helps to prevent runtime errors.
To use generics, you must specify a type parameter within angle brackets (e.g., <E>
) when declaring a class or interface. For example, the List
interface in Java has a type parameter E
that represents the type of elements in the list:
public interface List<E> {
// ...
}
You can then use the type parameter when declaring variables or methods. For instance, the add
method of the List
interface takes an argument of type E
:
public interface List<E> {
// ...
boolean add(E element);
}
To use a generic class or interface, you must specify a concrete type to replace the type parameter. For example, to create a list of integers, you would specify Integer
as the type parameter:
List<Integer> numbers = new ArrayList<>();
This creates a List
object that can only hold Integer
objects. If you try to add an object of a different type, you will get a compile-time error.
Generics also allow you to define methods with type parameters. For instance, the swap
method below takes two arguments of type T
and swaps their values:
public class Utils {
public static <T> void swap(List<T> list, int i, int j) {
T temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
You can then use this method with any type of list. For example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
Utils.swap(numbers, 1, 4);
// numbers is now [1, 5, 3, 4, 2]
List<String> words = Arrays.asList("apple", "banana", "cherry");
Utils.swap(words, 0, 2);
// words is now ["cherry", "banana", "apple"]
Generics can also be used with bounds to constrain the types that can be used as type parameters. For instance, the Comparable
interface has a type parameter T
that extends Object
, which means that T
must be a subclass of Object
:
public interface Comparable<T> {
int compareTo(T o);
}
You can then specify that a type parameter must implement a certain interface or extend a certain class by using a bounded type parameter. For example, the max
method below takes a list of objects that implement the Comparable
interface and returns the maximum element:
public class Utils {
public static <T extends Comparable<T>> T max(List<T> list) {
T max = list.get(0);
for (T t : list) {
if (t.compareTo(max) > 0) {
Comments
Post a Comment