2013-08-07 56 views
0

我需要創建一個鏈表,並用容器中的「容器」和「元素」填充它。用其他列表中的單獨元素和元素填充java列表的最佳方法是什麼?

這是我的代碼:

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中的任何方法,使之更好(更簡潔,乾燥等)?

+0

你能繞過列表填充它的對象? –

+2

「更好?」是什麼意思? –

+0

@SotiriosDelimanolis它不是通信對象的責任......至少在我的對象模型中... – yashaka

回答

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()); 
+0

這將是更好的選擇,如果我的WebElements有.getExpectedElements()方法...但只有'容器'實現HaveExpectedElements接口並有此方法...做出LIst 的結果列表對我來說是不夠的,因爲我需要一些WebElement對列表元素的操作。 – yashaka

相關問題