Generics in java
Generics are a feature in Java that allow developers to create classes and methods that can work with different types of data. Here is an example of how to use generics in Java:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
strings.add("apple");
strings.add("banana");
strings.add("orange");
List<Integer> integers = new ArrayList<>();
integers.add(1);
integers.add(2);
integers.add(3);
printList(strings);
printList(integers);
}
public static <T> void printList(List<T> list) {
for (T item : list) {
System.out.println(item);
}
}
}
In this example, we define two different lists - one that contains strings and one that contains integers. We then call a printList method twice, passing each list as an argument. The printList method is defined with a generic type parameter T. This allows the method to work with any type of list. The method uses a for loop to iterate over the list and print each item to the console.
No comments:
Post a Comment