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?

1
  • Your question is a bit unclear... Do you want a List of these Objects or an array? Commented Aug 26, 2011 at 20:45

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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

4 Comments

Perfect! Thank you! I didn't realize you could nest type parameters like that.
You can also add to your answer how to instance and declare arrays too: BloomFilter<String>[] threadedEncrpytionFilters = new BloomFilter<String>[100];
@Marcelo: the whole point here is that your code wont compile.
@Zenzen you are right. Check this answer out: stackoverflow.com/questions/1025837/…
1

Consider this:

private static List<BloomFilter<String>> threadedEncrpytionFilters = 
    new ArrayList<BloomFilter<String>>();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.