[英]java.util.Map implementation with generics
I want to create an implementation of java.util.Map which only takes String as key and value. 我想创建一个java.util.Map的实现,该实现只将String作为键和值。
I tried several things 我尝试了几件事
abstract class BaseMap<String,String> implements Map<K,V>
this gives a compile error mebe because I am implementing the interface and not fulfilling the full definition of Key and Value 这会产生编译错误,因为我正在实现接口,但未实现键和值的完整定义
then I tried extending the interface to define types, it does nt let me do that as well 然后我尝试扩展接口以定义类型,它并没有让我也这样做
public interface IBaseMap<String, String> extends Map<K, V>
It still gives error "The type parameter String is hiding java.lang.String" 它仍然给出错误“类型参数字符串隐藏java.lang.String”
Please help, thanks in advance 请帮助,在此先感谢
You need to provide concrete types while extending an Interface of generics like: 在扩展泛型接口时,您需要提供具体类型,例如:
abstract class StringToStringMap implements Map<String, String> {
// ...
}
Or if you want to extend Map<K, v>
interface then: 或者,如果要扩展
Map<K, v>
接口,则:
interface IBaseMap extends Map<String, String> {
// ...
}
Do you really need inheritance here? 您真的需要继承吗? You should really avoid using it like this.
您应该真正避免像这样使用它。 You can work with composition in better way:
您可以以更好的方式处理合成:
class CustomMap<K extends String, V extends String> {
private Map<K, V> map;
public Map<K, V> getMap() {
return map;
}
}
Now, you can instantiate your CustomMap
with only String
as type argument, which eventually is used as key and value for enclosed Map
. 现在,您可以仅使用
String
作为类型参数来实例化CustomMap
,该参数最终用作封闭Map
键和值。
In fact, no need to make the class generic at all, as specified by @TedHopp in comments. 实际上,根本不需要像@TedHopp在注释中指定的那样使类通用。 Just enclose a
Map<String, String>
: 只需封装一个
Map<String, String>
:
class CustomMap {
private Map<String, String> map;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.