使用Java中的Map和Consumer实现多态的示例。

huangapple go评论75阅读模式
英文:

Usage of polymorphism with Map and Consumer from Java

问题

我有一个类似这样的类

public class Foo {
private final Map<Step, Consumer<Step>> context = new LinkedHashMap<>();

public &lt;T extends Step&gt; void save(Consumer&lt;T&gt; consumer, T step) {
	this.context.put(step, (Consumer&lt;Step&gt;) consumer);
}

}


如你所见,我想要能够保存任何继承自`Step`的类到我的`Map`上下文中,但是我得到了以下错误

提供的 Consumer<T>,需要的 Consumer<Step>


是否有一种方法可以通过使用泛型来实现期望的结果?

我尝试过的一些方法是:

 - 将`Map`类型更改为`&lt;? extends Step&gt;`,但这会抛出一个新错误,因为当使用通配符`?`时,似乎你有一个只读的`Map`。
 - 像下面这样进行类型转换

public class Foo {
private final Map<Step, Consumer<Step>> context = new LinkedHashMap<>();

public &lt;T extends Step&gt; void save(Consumer&lt;T&gt; consumer, T step) {
	this.context.put(step, (Consumer&lt;Step&gt;) consumer);
}

}


后者似乎能够工作,但我在控制台上得到了一个`Unchecked cast`警告。如果这是正确的方法,我想知道它的缺点是什么,以及如何适当地检查它。
英文:

I have a class like this

public class Foo {
	private final Map&lt;Step, Consumer&lt;Step&gt;&gt; context = new LinkedHashMap&lt;&gt;();
	
	public &lt;T extends Step&gt; void save(Consumer&lt;T&gt; 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&lt;T&gt;, Required Consumer&lt;Step&gt;

Is any way to achieve the desired result by using generics?

Some things I tried are:

  • Changing the Map type to &lt;? extends Step&gt;, but this throw a new error, because it seems that when you use the wildcard ? you have a read-only Map.
  • Typecasting like below
public class Foo {
	private final Map&lt;Step, Consumer&lt;Step&gt;&gt; context = new LinkedHashMap&lt;&gt;();
	
	public &lt;T extends Step&gt; void save(Consumer&lt;T&gt; consumer, T step) {
		this.context.put(step, (Consumer&lt;Step&gt;) 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.

huangapple
  • 本文由 发表于 2023年3月7日 00:56:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定