views:

116

answers:

2

I'm sure that my problem is common and I almost sure that it doesn't have easy solution.

So: I have an interface:

public interface Task<E> extends Serializable {
    Task<E>[] splitTask (int partsNum);
    E mergeSolutions (E... solutions);
    E solveTask ();
    E getSolution ();
    Integer getId ();
    void setId (Integer id);
}

And I also have its implementation - BubbleSortTask, its code isn't interesting. The main idea of this design: we can split huge task to subtasks, solve every subtask and then merge solutions:

    Integer[] array = {1, 4, 9, 3, 3, 0, 8, 2, 6};
    BubbleSortTask bst = new BubbleSortTask (array);
    Task[] ts = bst.splitTask (2);
    for (Task t : ts) {
        t.solveTask ();
    }
    bst.mergeSolutions (((BubbleSortTask)ts[0]).getSolution (),
                        ((BubbleSortTask)ts[1]).getSolution ());

It works well. But in general case I shouldn't know anything about concrete implementation, I want to do something like this:

public void processTask (Task t, int subtasksNum) {
    Task[] ts = t.splitTask (subtasksNum);
    for (Task t : ts) {
        t.solveTask ();
    }
    Object[] solutions = new Object[subtasksNum];
    for (int i = 0; i < subtasksNum; i++) {
        solutions[i] = ts[i].getSolution ();    
    }
    t.mergeSolutions (solutions);
}

This code doesn't work, I get ClassCastException from mergeSolutions (solutions). But I hope that the main idea is clear. I wonder how should I solve this problem?

+8  A: 

Specify the interface in terms of a Collection, instead of an array.

public interface Task<E> extends Serializable {
    Collection<? extends Task<? extends E>> splitTask (int partsNum);
    E mergeSolutions (Collection<? extends E> solutions);
    E solveTask ();
    E getSolution ();
    Integer getId ();
    void setId (Integer id);
}
erickson
I'll try tomorrow)
Roman
Thank's, now it works good
Roman
A: 

I think your problem is passing Object[] to the mergeSolutions() while the specific t.mergeSolutions() is expecting E[], whatever your E type is.

I'm no expert, but I think you might need to use some reflection to get your E type and instantiate your solution as E[] based on that information

DJ