所以我一直在寻找这个问题的答案,但我不确定它是如何工作的。
我正在尝试创建 BloomFilter 对象的列表。
BloomFilter 的类定义为:
public class BloomFilter<E> implements Serializable { ...
允许用户选择要进入过滤器的元素类型。就我而言,我需要字符串。
在程序的其他地方,我需要 4 个 BloomFilter
对象。
我的问题是:如何初始化以下行?
private static BloomFilter<String> threadedEncrpytionFilters[] = null;
threadedEncryptionFilters = ???
这看起来类似于创建 ArrayList 列表?这也可以吗?
So I've been searching a while for the answer to this and I'm just not sure how it works.
I'm trying to make a list of BloomFilter<String>
objects.
The class definition for the BloomFilter is:
public class BloomFilter<E> implements Serializable { ...
The <E>
allows the user to pick what type of elements are going into the filter. In my case, I need strings.
Somewhere else in the program, I need 4 BloomFilter<String>
objects.
My question is: How do I initialize the following line?
private static BloomFilter<String> threadedEncrpytionFilters[] = null;
threadedEncryptionFilters = ???
This seems similar to creating a list of ArrayLists? Is that also possible?
发布评论
评论(3)
看到有人已经回答了这个问题后,我想删除这个答案,但我从评论中看到人们仍然感到困惑,所以这里是:)
该规范明确指出,你想做的事情是非法的。含义:
无法编译。您无法创建具体泛型类的数组。当涉及到泛型时,您只能存储在数组中:
解决问题的方法是,如前所述,将数组更改为
List>
。如果考虑到 Java 在不同阶段(编译、运行时等)如何处理泛型类型,这种行为实际上是非常合乎逻辑的。了解这一点后,您将看到具体泛型类型的数组不是类型安全的。这是关于这个主题的非常好的读物:http://www.angelikalanger.com/ GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104
After seeing that someone alread answered this question I wanted to remove this answer but I see by the comments that people are still confused so here it goes :)
The specification clearly states, that what you want to do is illegal. Meaning:
won't compile. You can't create an array of concrete generic classes. When it comes to generics you can store in arrays only:
The workaround to your problem is, as already stated, to change the array to a
List<BloomFiler<String>>
.This behaviour is actually pretty logical if you take into account how Java handles generic types at different stages (compile, runtime etc). After understanding that you'll see that arrays of concrete generic types wouldn't be type-safe. Here's a mighty good read on this subject: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ104
考虑一下:
Consider this: