views:

109

answers:

2

Hi all

Just wondering if you're able to help me with my problem. This has probably come about by my not knowing the right keywords to search for.

This is not homework, just anonymised...

I have an interface and a bunch of implementing classes:

interface Fruit
Banana implements Fruit  
Apple implements Fruit  
....

I have a Fruit utilities class. In this is a method that takes any sort Fruit and slices it.

public static Fruit[] slice(Fruit f, int pieces)

How can I declare the Fruit array to be of the same type as the Fruit I pass to the method?

ie How can I automate:

Fruit[] a = new Apple[pieces];

if I give it an Apple?

.

edit:clarification

I'll have code like this:

Fruit a = new Apple();
Fruit b = new Banana();
Fruit[] slices1 = FruitUtil.slice(a, 3); //slices1 should be an Apple
Fruit[] slices2 = FruitUtil.slice(b, 3); //slices2 should be a Banana
Fruit newApple = FruitUtil.copy(a); //newApple should be an Apple

How do I write slice(Fruit f, int slice) or copy(Fruit f) method such that I create the same type of Fruit as what I passed in the arguments (without having to override the method for each type, or doing instanceof checks)

+6  A: 

Firstly I suggest giving up arrays of references. Use List instead. Then it is relatively simple:

public static <T extends Fruit> List<T> slice(T fruit, int pieces)
Tom Hawtin - tackline
+1  A: 

Alternatively you can use reflection: Array.newInstance(f.getClass(), pieces)

Timothy Pratley