【问题标题】:Getting Consecutive Pairs from a List从列表中获取连续对
【发布时间】:2015-01-20 18:49:39
【问题描述】:

我正在重构一些代码,其中一部分看起来像这样 -

    public void addElementPairsToConfig(final Config config, final Element element1, final Element element2, final Element...elements) throws Exception {  
        config.addDependency(element1, element2);
        Element currentElement = element2;
        for (int i = 0; i < elements.length; i++) {
        config.addDependency(currentElement, elements[i]);
        currentElement = elements[i];
        }   
    }

我认为它应该是这样的 -

    public void addElementPairsToConfig(final Config config, final Element...elements) throws Exception {        
        for (Pair<Element, Element> pair : elements.getNextPair()) {
        config.addDependency(pair.getFirst(), pair.getLast());
        }   
    }  

我知道Apache Commons 有一个Pair 类,我将使用它,但找不到执行此操作的List util 方法,是否存在。我不介意自己写一个,但我宁愿不重新发明轮子,而是使用来自Apache CommonsGuava 的东西,如果它存在的话。

在 ruby​​ 世界中,我会使用 slice 之类的东西。

【问题讨论】:

    标签: java collections refactoring guava apache-commons


    【解决方案1】:

    您对方法签名的更改非常好。但是,您对方法实现的想法是过度设计。我建议保持简单:

    public void addElementPairsToConfig(final Config config, final Element...elements) throws Exception {        
        for (int i = 1; i < elements.length; i++) {
            config.addDependency(elements[i-1], elements[i]);
        }
    }  
    

    【讨论】:

    • 完美,优雅多了!我不喜欢使用 i 进行迭代,但我认为在这种情况下这是最好的方法。
    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 2016-08-08
    • 2015-02-06
    • 2023-01-27
    • 1970-01-01
    • 2011-12-06
    • 2021-09-03
    相关资源
    最近更新 更多