1

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?

javaPlease42
  • 3,765
  • 3
  • 32
  • 56
theangryhornet
  • 383
  • 2
  • 4
  • 14

3 Answers3

4

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:

BloomFilter<String> threadedEncrpytionFilters[] = new BloomFilter<String>[4];

won't compile. You can't create an array of concrete generic classes. When it comes to generics you can store in arrays only:

  • raw types
  • unbounded wildcard parameteriezd types

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

Mateusz Dymczyk
  • 14,171
  • 8
  • 55
  • 90
2
List<BloomFilter<String>> list = new ArrayList<BloomFilter<String>>();
list.add(new BloomFilter<String>());
list.add(new BloomFilter<String>());
list.add(new BloomFilter<String>());
// ... and so on
Marcelo
  • 10,928
  • 1
  • 33
  • 51
Brian Kent
  • 3,574
  • 1
  • 23
  • 31
1

Consider this:

private static List<BloomFilter<String>> threadedEncrpytionFilters = 
    new ArrayList<BloomFilter<String>>();
MByD
  • 129,681
  • 25
  • 254
  • 263