Suppose I am having a Collection of object:
List<String> myList = populateMyArrayList();
//Here I am having an ArrayList with 1000 elements
Which is the better approach:
1 : Mergesort then Binary Search
Collections.sort(myList);
int keyIndex = Collections.binarySearch(myList, key);
2 : Sequential Search
for(String s : myList){
if(s.equals(key)){
return s;
}
}
Should there be a difference in searching approach based on the size of the collection to be searched? If YES then how to decide.
EDIT1: Suppose I have to search the list a couple of times, and no new elements will be added in the list.
EDIT2: I could have gone for a HashSet
, but I am actually having a List<CustomObject>
and I can search the List
multiple times based on different attributes of CustomObject. So I can't have a overridden equals
method in my CustomObject
myList.contains(key)
. – HibernateHashSet
but without further informations these are just suppositions. – Supersede