使用其他列表中的单独元素和元素填充java列表的最佳方法是什么?

时间:2013-08-07 17:41:18

标签: java list collections linked-list

我需要创建一个链表并用"容器"填充它。和"元素"来自容器。

这是我的代码:

public List<WebElement> getExpectedElements(){
    List<WebElement> list = new LinkedList<WebElement>(Arrays.asList(
            inetConnection,
            wiredConnection,
            phonesConnection,
            usbConnection,
            wifiConnection
    ));
    list.addAll(inetConnection.getExpectedElements());
    list.addAll(wiredConnection.getExpectedElements());
    list.addAll(phonesConnection.getExpectedElements());
    list.addAll(usbConnection.getExpectedElements());
    list.addAll(wifiConnection.getExpectedElements());
    return list;
}

java中是否有任何方法可以使它更好(更简洁,干燥等)?

1 个答案:

答案 0 :(得分:2)

你至少可以引入一个循环:

List<WebElement> containers = Arrays.asList(inetConnection,
        wiredConnection,
        phonesConnection,
        usbConnection,
        wifiConnection);
List<WebElement> list = new LinkedList<WebElement>(containers);
for (WebElement e : containers)
    list.addAll(e.getExpectedElements());