简体   繁体   English

储存未来 <Double> 在ArrayList中

[英]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 或与此相关的任何Future对象,它将在可调用对象完成运行时自动从Future值转换为所需的对象类型(在这种情况下为Double),还是最好让它具有

 ArrayList<Double>calculations = new ArrayList();

and simply check for the callable's completion to add to the ArrayList? 并简单地检查可调用项的完成以添加到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?" 如果您不担心RAM,那么“无论是哪个”问题的一个很好的解决方案是“为什么不同时使用两个?”

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. 如果没有编写一些代码来填充它,就无法神奇地获得一个double列表。 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. 并避免单独列出所有结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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