Generic methods have type parameters that specify operable data types. Wildcards represent unknown types, upper wildcards specify that the type is a subclass of a given type or itself, and lower wildcards specify that the type is a parent class or itself.
The difference between Java generic methods and wildcards
Introduction
Generics It is a powerful tool in Java that allows developers to create reusable code without having to worry about data type incompatibilities. Generic methods and wildcards are two mechanisms that further enhance the capabilities of generics. This article will explore their differences and show how to use them through practical examples.
Generic methods
A generic method is a method with type parameters. Type parameters specify the data types that the method can use. For example, the following generic method can operate on a list of any type:
public static <T> void printList(List<T> list) { for (T item : list) { System.out.print(item + " "); } System.out.println(); }
A generic method can be called by specifying a type parameter when using the method:
List<String> names = new ArrayList<>(); names.add("John"); names.add("Mary"); printList(names); // 输出:John Mary
Wildcards
Wildcards are special syntax used to represent unknown types. They are often used to create upper or lower bounds on generics.
For example, the following generic method uses an upper bound wildcard to get the superclass of all objects in the list:
public static <T> List<Class<?>> getSuperclasses(List<? extends T> list) { List<Class<?>> superclasses = new ArrayList<>(); for (T item : list) { superclasses.add(item.getClass().getSuperclass()); } return superclasses; }
Practical case
Consider The following case: We have an animal class that implements the Animal interface, and we want to have a method to print a list of animals.
Generic method
We can create a generic method to print any type of Animal:
public static <T extends Animal> void printAnimals(List<T> animals) { for (T animal : animals) { System.out.println(animal.getName()); } }
Wildcard
We can also use wildcards to represent any subclass of Animal:
public static void printAnimals(List<? extends Animal> animals) { // 使用上限通配符 for (Animal animal : animals) { // 使用上限通配符 System.out.println(animal.getName()); } }
In both cases, we can use a single method to print a list of different types of animals. However, generic methods provide type safety because it forces the type parameters to inherit the Animal interface, whereas wildcards do not provide this guarantee.
The above is the detailed content of What is the difference between Java generic methods and the use of wildcards?. For more information, please follow other related articles on the PHP Chinese website!