2009-10-06 55 views
0

是否有一種簡單的方法/庫來檢查和調整參數以保持在列表邊界內?簡化的Java列表邊界檢查

這裏一個長的樣品:

if (fromIndex < 0) { 
    fromIndex = 0; 
} 
if (fromIndex > list.size() - 1) { 
    fromIndex = list.size() - 1; 
} 

if (toIndex < 0) { 
    toIndex = 0; 
} 
if (toIndex > list.size() - 1) { 
    toIndex = list.size() - 1; 
} 

list.subList(fromIndex, toIndex); 

我知道我可以移動list.size() - 1到一個變量,並做在索引檢查的提取物的方法,以除去冗餘碼。但對於這個簡單的任務,它似乎仍有點冗長。

回答

5
public int sanitize(int index) { 
    return Math.max(0, Math.min(index, this.length-1)); 
} 
+0

小記:'list'或'listSize'也應該是參數 – naltatis 2009-10-06 12:31:02

+0

@tatilans:真,在這個片段中,看起來有點像上下文靜態方法。然而,布賴恩建議包裝一個現有的列表是一個更好的方式來實現這一點(更靈活,更少侵入,更少的樣板代碼),在這種情況下,「列表」可能是最終的成員領域。 – 2009-10-06 12:42:52

+0

好的。我將它改爲this.length。如果它只是增加了更多的困惑,我會回滾:) – Zed 2009-10-06 12:57:10

3

如果你想檢查所有訪問到您的列表,在我看來,要在類內包裝列表實現List接口和攔截訪問的方法來檢查/修改訪問索引。

例如

List sanitised = new SanitisedList(existingList); 

這是Decorator模式的示例。請注意,您只需要定義一個類(SanitisedList),您可以將其應用於您擁有的任何列表。使用Zed's answer進行漂亮的邊界檢查。

0

您可以使用三元運算:

int listMax = list.size() - 1; 
list.subList(fromIndex < 0 ? 0 : (fromIndex > listMax) ? listMax : fromIndex, 
       toIndex < 0 ? 0 : (toIndex > listMax) ? listMax : toIndex);