Java: How to set a default for "T" in SomeClass<T>?
Is there a way to specify a default type for a generic template?
Let's say I have a Monkey
class. Monkeys can live in different Environment
s, such as Jungle
or Zoo
:
public class Monkey<T extends Environment> { T home; ... public T getHome() { return home; } }
Is there a way to specify a default for T
, s开发者_如何学编程o I can use the type Monkey
instead of Monkey<?>
without getting a compiler warning?
EDIT
In other words, is there a way to get rid of the "raw type" warning without having to explicitly suppress it?
No, you can't do that. Generic parameters don't have default values. You could re-organize your type hierarchy so that there's a GenericMonkey and a DefaultMonkey that sets the generic parameter to your desired default.
No you can't: http://en.wikipedia.org/wiki/Comparison_of_Java_and_C%2B%2B
Generic type parameters cannot have default arguments.
What about making something like this:
public class Monkey extends Monkey<YourType>
Obviusly you'll "waste" the ability to inherit.
EDIT 1: Another interesting thing is do the reverse of what I suggested,
public class Monkey<T> extends Monkey
In this case all generics class Monkey inherits Monkey, in some cases, this is a very interesting thing (expecially when you notice that some instance-methods fits in all classes without requiring the generic). This approach is used in Castle ActiveRecord (I've seen it used in C#, not in Java), and I find it beautiful.
Jen, your question doesn't put any context around why you want to use a generics. It would really be helpful if you stated what it is you are trying to do and why you are using generics. Generics exist IMHO mainly to avoid having to do class casts everywhere when putting things into and taking them out of collections that are designed to be generic holders of types. This kinda implies iteration over a bunch of things, but not necessarily.
My point is, I didn't see any part of your class or code that required being able to create a custom version of the monkey class that required iterating over environments. If this is not the case, you probably don't even need generics. Instead, you probably want dependency injection. The monkey class should have a constructor that takes an environment. Environment is an interface (or simple base class). The interface has several default operations like getBathroomLocation() and getFoodLocation(). Instead of using generics to create a type of monkey that lives in the zoo, you create a monkey and inject the dependency of which environment it lives in.
Monkey monkey = new Monkey(new CostaRicaJungle());
Later on, you can set this environment to something different. The wild monkey gets captured, and you now do
monkey.setEnvironment(new BronxZoo());
Later, the monkey gets an living condition upgrade, and you do a
monkey.setEnvironment(new SanDiegoZoo());
Why not just use the base class of the Generic? Monkey<Environment>
?
精彩评论