2012-02-07 79 views
1

我有自定義對象的數組CustomClass [] customArr其中CustomClass就像對象數組

Class CustomClass{ 

private String key; 
private String value; 

//getter & setters 

} 

現在我想通過一個特定的value.What搜索該陣列是做的最好辦法這個 ?

回答

5

實施equals()。確保您遵守該方法的合同。另外,如果你經常搜索並且數組很大,那麼你可能想考慮一個更好的數據結構,例如, Set的其中一個實現,如果您對數據結構中特定實例的存在感興趣或者想要通過密鑰進行搜索的Map的實現之一。詳情請參閱java.util

注意一些java.util的數據結構可能需要提供自己的hashCode()(例如HashSet)版本以及一些可能需要您實現Comparable接口或提供Comparator(例如TreeSet)。

如果您提供自己的hashCode()版本,請確保它與您的equals()(請參閱equals()的javadoc)一致。

如果您確實必須使用數組,請考慮Arrays.binarySearch()的其中一個版本。請注意,您只能在有序數組上使用它。

0

實現類比。然後你可以使用java.util.Arrays來搜索和排序你的數組。

Class CustomClass implements Comparable { 

private String key; 
private String value; 

//getter & setters 

public int compareTo(Object other){ 
    if(other instanceOf CustomClass) 
    { 
     CustomClass otherCustomClass = (CustomClass) other; 
     int val = this.key.compareTo(otherCustomClass.key ); 
     if(key != 0) return key; 
     return this.value.compareTo(otherCustomClass.value); 
    } 
    return -1; 
} 

}