I am currently working on homework for the Java programming course that I am taking. I do not require an exact answer, but for some recommendations.
The problem I'm working on is this:
I have a filter class that implements the Filter interface. This interface has only one method - matches(T element)
I set up my filtering method to test Integer, which is passed in for simplicity.
There is also a decorator class that decorates a collection class only to display objects that pass the filter.
I'm having problems with the contains (Object o) method working correctly.
Basically, the contains(Obj o) method in the FilteredCollection class must first check if the object passes through the filter, and then, if so, call the undecorated contains() method on that object.
Assuming that I want to use this FilteredCollection class with many different types of filters, how can I determine which type of object will be passed, and then be able to pass this object to the current filter that is implemented.
Here is my PrimeNumberFilter Class:
public class PrimeNumberFilter implements Filter<Integer> { public boolean matches(Integer e) { int n = e.intValue(); if (n != 2 && n % 2 == 0) { return false; } for (int i = 3; i * i <= n; i += 2) { if (n % i == 0) { return false; } } return true; } }
Then here is my abbreviated FilteredCollection Class:
class FilteredCollection<T> implements Collection<T> { Collection<T> fc; Filter<T> currentFilter; private FilteredCollection(Collection<T> coll, Filter<T> filter) { this.fc = coll; this.currentFilter = filter; } public static <T> FilteredCollection<T> decorate(Collection<T> coll, Filter<T> filter) { return new FilteredCollection<T>(coll, filter); } public boolean contains(Object o) {
The object passed to the contains method must pass a filter, in this case a PrimeNumberFilter .
The error I get is that she wants to overlay the object on type T, and I know that this will never work due to erasure.
I did a lot of research and I boiled it to use reflection.
The only hint my instructor will give me is that the object has only a few methods that I can use, and I must use one of them.
Thank you for your help!
EDIT:. One of the requirements of the project is NOT to attach the object to T in any method. Therefore, although these answers are great, I cannot use them.