this question is partially related to my last question.
I have a generic class representing a collection of generic objects:
public interface MyObject<N extends Number>{}
public interface MyCollecion<N extends Number> {
public foo(MyObject<N> obj)
}
In my design these collections of objects are constructed by a client class (let's call it CollectionBuilder) through an abstract class approach:
public interface AbstractCollectionFactory {
public abstract <N extends Number> MyCollection<MyObject<N>> createCollection(String collectionType);
}
Generic collections should be constructed this way:
public class CollectionBuilder{
AbstractCollectionFactory f;
public void buildDoubleCollection(){
MyCollection<MyObject<Double>> c = f.<Double>createCell("MyType");
}
public void buildIntegerCollection(){...}
}
Ok.Since here all ok. CollectionBuilder is aware of what is the generic concrete type to specify (Double in this case) and can build correctly. I can compile this with no warning and all should work fine.
Now I have a question related both to generics and the design of my program.
I have another class in my application that need to use the collection built by CollectionBuilder (let's call this class UserClass). The UserClass:
- Doesn't need to know of which particular concrete type are its collection (
MyCollection<MyObject<Double>>
orMyCollection<MyObject<Integer>>
). - perform some operations on these collections invoking some methods defined in MyCollection interface.
- I would not want to add a generic type to it.
In the situation described, is that a bad idea do not parametrize the generic class MyCollection insied UserClass?
public UserClass{
MyCollection a; //warning
MyCollection<?> b; //no warning
public method(MyObject o){ //warning
a.foo(b); //compile
}
public method2(MyObject<?> o){
b.foo(o); //error do not compile
}
}
Java compiler always protest with a warning if I don't specify the generic parameter. Anyway from inside UserClass I don't know the concrete parameter (and I would like to don't know it) and even declaring it with "?" don't allow me to call method foo on MyCollection.
So the question are:
- not parameterizing a reference to a generic type is always a bad thing?
- if answer at 1 is NO, is this a right situation for not doing it?
- if answer at 1 is YES, how can I use MyCollection method from inside UserClass without knowing their generic types?
- Is mine a bad design ?
I hope to have been clear. I've be struggling on this problem from days, and I have no idea. Please help me.