Home > Java > Use two generics to implement the interface

Use two generics to implement the interface

王林
Release: 2024-02-09 10:45:09
forward
462 people have browsed it

php editor Xinyi will introduce to you the method of using two generics to implement the interface. Generics are a feature that enables the use of type parameters in programming languages, which can increase the flexibility and reusability of code. When implementing an interface, we can use generics to specify the type parameters in the interface, so that different data types can be used in different scenarios. This method can make our code more versatile and scalable and improve development efficiency. In this article, we will explain in detail how to use two generics to implement the interface, and give sample code for your reference.

Question content

I have a task for my homework but I can't get over it.

The code of the transformer interface is as follows:

public interface transformer<from, to> {
    to transform(from value);
}
Copy after login

So far, the code for the personsubscribertransformer class looks like this:

public class PersonSubscriberTransformer<FROM, TO> implements Transformer {
    private Predicate<Person> predicate;
    public PersonSubscriberTransformer(Predicate<Person> predicate) {
        this.predicate = predicate;
    }
    @Override
    public Object transform(Object value) {
        return null;
    }
  }
Copy after login
The parameters of the

transform method should be list<person> and it should return a list<subscriber>. When I change the parameters, I get an error message saying that I should pull the method to the transformer interface.

What is the solution to implement this method in the right way?

Workaround

Based on the expected signature of transform, from should be list<person> and to should be list<subscriberphpcngt phpcn. Classes themselves should not be generic.

public class PersonSubscriberTransformer implements Transformer<List<Person>, List<Subscriber>> {
    // constructor...
    
    @Override
    public List<Subscriber> transform(List<Person> persons) {
        // complete this method...
        return null;
    }
}
Copy after login

The above is the detailed content of Use two generics to implement the interface. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template