Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use generics without collections

Tags:

java

Let's say I have the folowing:

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

And if I want to call myList.add(myApple), Java expects from myApple to have type of Apple, not any others (except subclasses of course). But what if I want to have an object (Blender) and have different method signatures according to type declared inside <> and without method overloadings; like 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's are permitted

Is it possible?

like image 416
TomatoMato Avatar asked Feb 15 '13 18:02

TomatoMato


2 Answers

you are looking for Generic 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());
   }
 }
like image 82
PermGenError Avatar answered Oct 06 '22 00:10

PermGenError


Yes it is:

public class Blender<T> {
   public void blendIt(T arg) { ... }
}
like image 39
NPE Avatar answered Oct 06 '22 00:10

NPE