How can I have several extensions of a class Fruit, and based on what class/type the object ist, execute the same method on this fruit but with different function?
Example: I’m using a FruitManager to add a new Fruit fruit = new Apple(); to the fruitstore. If this fruit is an apple, I want of course to add this to the apples list. Elso to bananas list.
Now if I have 10 sorts of fruits, I do no want to create 10 functions like addBanana(), addApple() and so on.
And I too do not want to have cluttering if-else statements for getting the right fruit list.
Can I samehow get the fruitlist just based on the type of object I’m adding?
class Fruit;
class Apple extends Fruit;
class Banana extends Fruit;
class FruitStore {
List<Fruit> apples = new ArrayList<Apple>();
List<Fruit> bananas = nwe ArrayList<Banana>();
}
class FruitManager {
FruitStore store;
//called from somewhere with Fruit fruit = new Apple();
addFruit(Fruit fruit) {
//how could things like this be done in one statement?
store.<get list apples or bananas>.add(fruit);
}
}
Making my kludge into an answer. Consider using a HashMap of
HashMap<Class<? extends Fruit>, List<Fruit>>. Something like this:I tested this with: