Using generics without collections

Say I have the following:

List<Apple> myList = new ArrayList<Apple>(); 

And if I want to call myList.add(myApple) , Java expects myApple be of type Apple and not others (except for subclasses, of course). But what if I want to have an object ( Blender ) and have different method signatures according to the type declared inside <> and without overloading the methods; So:

 Blender<Apple> Tool = new Blender<Apple>(); Tool.blendIt(new Apple()); //expects to have only apples in here Blender<Banana> OtherTool = new Blender<Banana>(); OtherTool.blendIt(new Banana()); //only Banana are permitted 

Is it possible?

+7
source share
3 answers

You are looking for a general class .

 class Blender<T>{ T t; public void blendIt(T arg){ //stuff } } class Test { public void method() { Blender<Apple> blendedApple = new Blender<Apple>(); blendedApple.blendIt(new Apple()); Blender<Bannana> blendedBannana = new Blender<Bannana>(); blendedBannana.blendIt(new Bannana()); } } 
+11
source

Yes this:

 public class Blender<T> { public void blendIt(T arg) { ... } } 
+2
source

In Java, generics are for Collections only. This is a general concept and applies to classes, methods, etc. You can create a generic class.

+1
source

All Articles