gpt4 book ai didi

java - 访问充当上限的通用集合的元素类型

转载 作者:行者123 更新时间:2023-12-02 09:15:23 25 4
gpt4 key购买 nike

我想编写一个通用容器类。两个类型参数代表所包含元素的类型,以及一个用于查找元素的键类型。该集合具有一个 get 方法,该方法接受一个键并返回一个元素。因此该类的第一个签名将如下所示:

class MyContainer<E, K> {
...
E get(K k) { ...}
...
}

现在我想将 K 限制为类,这些类本身就是我想要用作键的元素的容器。

这些包含键的类是通过实现某个接口(interface)来指定的:

interface ProvidesKeys<E> {...}

然后我有具体的实现,例如

class SomeInts implements ProvidesKeys<Integer> {...}

这意味着 SomeInts 从 Integer 中选择一些可以用作键的元素。

我想像这样使用MyContainer:

MyContainer<String, SomeInts> myContainer = new MyContainer<>();
...
myContainer.get(3);

问题是 3 的类型是 Integer,而不是 SomeInts。所以我最初的 MyContainer 方案不再起作用了。

有没有办法限制 K 以便我可以访问 key 容器的元素类型?

我已经尝试过

class MyContainer<E, K extends ProvidesKeys<K> {....}

和通配符形式,但没有任何东西可以让我访问 key 提供类型的元素类型,所以我可以有一个正确的 E get(X k) {...} 方法!?我是否必须引入第三个类型变量来表示关键元素类型(尽管它隐含在关键容器中)?

最佳答案

Do I have to introduce a third type variable to represent the key element type (although it is implicit in the key container)?

是的。你做。除了将其作为参数之外,没有其他方法可以访问该类型。

关于java - 访问充当上限的通用集合的元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59038014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com