Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map to Class that Implements Interface

I currently have

class A {...}
interface B {...}

What I would like to have is some equivalent of

HashMap<String, A implements B>

i.e., that a String maps to any instance of A that implements B. But that syntax doesn't compile. Is there any way to map to a class that implements an interface? Note also that A is not generic, so I can't do something like

A<? implements B>
like image 574
Sherz Avatar asked Dec 02 '16 15:12

Sherz


People also ask

What are the classes that implements Map interface?

There are three classes to implement maps. These three classes are HashMap, LinkedHashMap, and TreeMap.

Can Map implements Collection interface?

1. Map implements collection interface? Explanation: Collection interface provides add, remove, search or iterate while map has clear, get, put, remove, etc. 2.

What is a class called that implements an interface?

Any class that inherits a parent class, or implements an interface is a "Polymorph" of the parent class / interface.

How are interfaces implemented in a class?

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.


Video Answer


1 Answers

It is possible to be done in a generic context, for instance, in a generic method:

public <T extends A & B> void method() {
    Map<String, T> map = new HashMap<>();
}

Unfortunately, we can't apply these multiple restrictions to wildcards.

like image 117
Andrew Tobilko Avatar answered Sep 24 '22 23:09

Andrew Tobilko