2014-12-08 34 views
2

我有一個ArrayList。該數組可以包含4個項目或4000個項目。我正在尋找中間4件物品。我的猜測是得到size/2 -2 +2。什麼是最有效的方式來做到這一點,你如何處理奇數?如何獲得Arraylist的中心4()

if (comparables.size() > 4) { 
      int size = comparableVehicles.size(); 
      System.out.println("size " + size); 
      int middle = size/2; 
      System.out.println("middle " + middle); 
      int bottom = middle - 2; 
      System.out.println("bottom " + bottom); 

      this.comparables = comparables.subList(bottom, bottom + 4); 
} 

回答

1

您正在使用的sublist調用可能是最有效的方法。關於奇怪大小的清單 - 按照定義,它們沒有「中間四個要素」。無論你如何採取四個要素,它們將永遠是靠近一方或另一方的一個要素。你可以做的最好的事情是做出良心決定,採取哪一方面,並​​堅持下去。在你的代碼片段中,使用整數除法事實決定讓「中間」更接近列表的開始。 TL; DR - 你的代碼很好。

+0

好,太好了,謝謝。 – 2014-12-08 07:47:46