Posts

Showing posts with the label generics

Java generics for optional single value or collection

Java generics for optional single value or collection I'm trying to define a container for a whole bunch of classes as some parts of the code will make more sense with a collection but other places will make sense with single values. Ideally I'd like to do this: public class AllModes<T> { private T<Car> car; private T<Boat> boat; private T<Train> train; private T<Plane> plane; ...40 more of these... } then I'd like to use the class like: AllModes<List> allModes; AllModes<Optional> oneOfEachMode; But I get the error I get is "The type T is not generic; it cannot be parameterized with arguments " The reason I'm defining these in multiple variables and not a single HashSet based on a superclass is I want to have get methods that return the correct types to avoid consumers of this class needing to cast down everywhere as each object has its own distinct fields. I also considered just storing a single value l...

Why do I have generic array creation error? [duplicate]

Why do I have generic array creation error? [duplicate] This question already has an answer here: class Generic<T> {} Generic<Object> gib; gib = new Generic<Object>[5]; // here is the line throwing Generic array creation error I don't understand why this sample should be considered generic array creation, because the generic array creation I've seen so far is created in the form like Generic<T>[SIZE] , with an unknown type parameter. But in this sample, I explicitly set the type parameter to Object , I guess my understanding of generic array must have some flaws, hope someone could help. Generic<T>[SIZE] Object This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question. In general generics and arrays don't mix well. Arrays are expected to enforce runtime checks like Object arr = new String[2]; (this will be OK), arr[1] = 1; this will...