Reputation: 5528
I have an array of custom objects CustomClass[] customArr where CustomClass is like
Class CustomClass{
private String key;
private String value;
//getter & setters
}
Now I want to search this array by a particular value.What is the best way to do this ?
Upvotes: 1
Views: 508
Reputation: 27233
Implement equals()
. Make sure you comply with the contract of the method.
Also, if you search often and the array is large you probably want to consider a better data structure for this, e.g. one of the implementations of Set
if you're interested in the presence of particular instances within the data structure or one of the implementations of Map
if you want to search by a key. See java.util
for details.
Note that some of the data structures in java.util
may require you to provide your own version of hashCode()
(e.g. HashSet
) and some may require you to implement Comparable
interface or provide a Comparator
(e.g. TreeSet
).
If you provide your own version of hashCode()
make sure it is consistent with your equals()
(see the javadoc for equals()
).
If you really must use an array, then consider one of the versions of Arrays.binarySearch()
. Note that you can only use it on sorted arrays.
Upvotes: 5
Reputation: 1961
Implement Comparable. Then you can use java.util.Arrays
to search and sort your array.
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;
}
}
Upvotes: 0