Home > Java > javaTutorial > How Can Generics Eliminate Typecasting When Retrieving Objects from Heterogeneous Collections?

How Can Generics Eliminate Typecasting When Retrieving Objects from Heterogeneous Collections?

Susan Sarandon
Release: 2024-12-24 00:19:10
Original
286 people have browsed it

How Can Generics Eliminate Typecasting When Retrieving Objects from Heterogeneous Collections?

Overcoming Typecasting with Generics in Return Types

In OOP programming, classes often maintain collections of related objects. For instance, an Animal class might keep track of a list of friends, which can be instances of various subclasses such as Dog and Duck.

Traditionally, retrieving specific friends from this list requires typecasting due to the heterogeneous nature of the collection. This results in code like:

Mouse jerry = new Mouse();
jerry.addFriend("spike", new Dog());
jerry.addFriend("quacker", new Duck());

((Dog) jerry.callFriend("spike")).bark();
((Duck) jerry.callFriend("quacker")).quack();
Copy after login

To avoid this cumbersome typecasting, consider using generics to make the return type of the callFriend method specific to the correct subclass. However, in this specific scenario, specifying the return type as a parameter like:

public <T extends Animal> T callFriend(String name, T unusedTypeObj) {
    return (T)friends.get(name);
}
Copy after login

is not helpful since the unused type parameter provides no additional information at runtime.

Instead, a workaround involves passing the class of the desired type as an argument to callFriend:

public <T extends Animal> T callFriend(String name, Class<T> type) {
    return type.cast(friends.get(name));
}
Copy after login

With this implementation, the method call becomes:

jerry.callFriend("spike", Dog.class).bark();
jerry.callFriend("quacker", Duck.class).quack();
Copy after login

This solution eliminates runtime typecasting and ensures that the returned object can safely be cast to the desired subclass.

The above is the detailed content of How Can Generics Eliminate Typecasting When Retrieving Objects from Heterogeneous Collections?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template