Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to set a default for "T" in SomeClass<T>?

Tags:

java

generics

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 Environments, 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, so 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?

like image 775
Tony the Pony Avatar asked May 23 '11 18:05

Tony the Pony


People also ask

How do I restrict a generic type in Java?

Java For Testers Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class.

How do you declare a generic class in Java?

To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.


2 Answers

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.

like image 192
Isaac Truett Avatar answered Sep 29 '22 16:09

Isaac Truett


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.

like image 29
Francesco Belladonna Avatar answered Sep 29 '22 16:09

Francesco Belladonna