kag*_*ag0 4 java generics recursion types
我正在尝试创建一个将集合作为键的Map实现.
你甚至把这个难题称为什么?
做类签名的正确方法是什么?
class SubClass <K extends Collection<E>, V> implements Map<K, V>
Run Code Online (Sandbox Code Playgroud)
^^语法不正确,但表明我想做什么.
class SubClass <K extends Collection<K>, V> implements Map<Collection<K>, V>
Run Code Online (Sandbox Code Playgroud)
^^结果在SubClass中,您永远不能声明泛型类型.K是无限递归的.它也没有描述我正在寻找的行为类型.
class SubClass <K , V> implements Map<K, V>
Run Code Online (Sandbox Code Playgroud)
^^不强制K需要成为Collection的约束
class SubClass <K extends Collection, V> implements Map<K, V>
Run Code Online (Sandbox Code Playgroud)
^^不允许我们知道Collection的泛型类型
class SubClass <E, K extends Collection<E>, V> implements Map<K, V>
Run Code Online (Sandbox Code Playgroud)
^^工作,但相当笨重
您需要Collection元素类型的类型参数,Collection如果需要,可能需要实际类型的类型参数,以及值的类型参数.
class SubClass<E, K extends Collection<E>, V> implements Map<K, V> { ... }
Run Code Online (Sandbox Code Playgroud)
如果您不需要特定Collection类型,则可以使用
class SubClass<E, V> implements Map<Collection<E>, V> { ... }
Run Code Online (Sandbox Code Playgroud)
关于你的问题的各种评论
public class Example {
public static void main(String[] args) throws Exception {
Whatever<Self> s = new Whatever<>();
}
}
class Self extends ArrayList<Self> {
}
class Whatever<E extends Collection<E>> {
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
404 次 |
| 最近记录: |