简体   繁体   中英

Storing Future<Double> in ArrayList

If you have

 ArrayList<Future<Double>>calculations = new ArrayList();

or any Future object for that matter, will it automatically convert from a Future value to the desired object type (Double in this case) when the callable is finished running, or would it be better to have

 ArrayList<Double>calculations = new ArrayList();

and simply check for the callable's completion to add to the ArrayList?

No conversion will take place.

For the question of "which would be better," you diverge somewhat into opinion. It depends on your application, but if you're trying to keep a list of calculations and their results the below would be a reliable way to do it. If you're not worried about RAM, then a good solution to the "either or" question is "why not both?"

With the below, you maintain references to both the calculations and the results, and you use an aggregate operation that makes it easier to do complex operations, should you need to do more later.

    List<Future<Double>> calculations = new ArrayList();
    List<Double> results = new ArrayList();

    calculations.stream().forEach((Future<Double> _item) -> {
        try {
            results.add(_item.get());
        } catch (InterruptedException ex) {
            // do something
        } catch (ExecutionException ex) {
            // do something
        }
    });

Presumably you are after a list of results like

List<Double> results

that are populated from the results of the Future calculations.

You cannot magically get a list of doubles without writing some code to populate it. What code you need to write depends on exactly what you want to do with the results. For example, how are you planning to check that all the Future tasks have completed?

You could do something as simple as

Double getResult(index i) {
    if ( calculations.get(i).isDone() )  {
        return calculations.get(i).get();
    } else {
        // Do something else
    }
}

and avoid a separate list for the results all together.

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