英文:
Usage of polymorphism with Map and Consumer from Java
问题
我有一个类似这样的类
public class Foo {
private final Map<Step, Consumer<Step>> context = new LinkedHashMap<>();
public <T extends Step> void save(Consumer<T> consumer, T step) {
this.context.put(step, (Consumer<Step>) consumer);
}
}
如你所见,我想要能够保存任何继承自`Step`的类到我的`Map`上下文中,但是我得到了以下错误
提供的 Consumer<T>,需要的 Consumer<Step>
是否有一种方法可以通过使用泛型来实现期望的结果?
我尝试过的一些方法是:
- 将`Map`类型更改为`<? extends Step>`,但这会抛出一个新错误,因为当使用通配符`?`时,似乎你有一个只读的`Map`。
- 像下面这样进行类型转换
public class Foo {
private final Map<Step, Consumer<Step>> context = new LinkedHashMap<>();
public <T extends Step> void save(Consumer<T> consumer, T step) {
this.context.put(step, (Consumer<Step>) consumer);
}
}
后者似乎能够工作,但我在控制台上得到了一个`Unchecked cast`警告。如果这是正确的方法,我想知道它的缺点是什么,以及如何适当地检查它。
英文:
I have a class like this
public class Foo {
private final Map<Step, Consumer<Step>> context = new LinkedHashMap<>();
public <T extends Step> void save(Consumer<T> consumer, T step) {
this.context.put(step, consumer);
}
}
As you can see, I wanna be able to save any class that is a child of Step
inside my Map
context, but I get the following error
Provided Consumer<T>, Required Consumer<Step>
Is any way to achieve the desired result by using generics?
Some things I tried are:
- Changing the
Map
type to<? extends Step>
, but this throw a new error, because it seems that when you use the wildcard?
you have a read-onlyMap
. - Typecasting like below
public class Foo {
private final Map<Step, Consumer<Step>> context = new LinkedHashMap<>();
public <T extends Step> void save(Consumer<T> consumer, T step) {
this.context.put(step, (Consumer<Step>) consumer);
}
}
The later seems to work, but I get a Unchecked cast
warning on my console. If this is the way to go, I would like to know what are the downsides of it and how would be an apropriate way to check for it.
答案1
得分: 2
编译器无法确认 Map 键的子类型是否与 Map 键值的 Consumer 的子类型相同。
您知道这一点,所以您知道未经检查的强制类型转换是安全的。
采用未经检查的强制类型转换。
英文:
The compiler has no way of confirming that the subtype of Step that's the key of the Map is the same subtype of the Consumer for the key's value in the Map.
You know that, so you know the unchecked cast is safe.
Go with the unchecked cast.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论