简体   繁体   中英

Use generics without collections

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?

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());
   }
 }

Yes it is:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM