Reputation: 379
I have a large list (about 12,000 objects) of custom Objects inside which I will have to search for a specific Object a number of times. As of now, I am mostly using brute force to find the object, but it becomes extremely slow as the list grows larger. This is how I search as of now:
List<MyObject> objectsToSearch; //List containing about 12000 objects
MyObject objectToCompare = new MyObject("this is a parameter"); //Object to compare with list
for(MyObject compareFrom : objectsToSearch){
if(compareFrom.equals(objectToCompare)){
System.out.println("Object found");
}
}
Surely there must be a better way to achieve this. Increasing performance becomes especially important since I will be needing to perform this operation multiple times.
Despite my research I haven't found any detailed tutorial. How do I achieve this?
Upvotes: 3
Views: 1279
Reputation: 20465
Are you sure that you really need a List? It seems that you are just checking the object for presence. If you don't need to keep the order of the objects and if it's sufficient to keep each object only once, consider using a Set instead, most probably HashSet.
Do not forget to implement equals() and hashCode() for the objects you store otherwise HashSet will not work.
Upvotes: 3
Reputation: 2541
If you have implemented equals method for your custom class correctly you can use the contains(Object o) method.
if(objectsToSearch.contains(objectToCompare)){
System.out.println("Object found");
Upvotes: 0
Reputation: 8292
Make your class MyObject
implement the Comparator
and then sort the list using Collections.sort() and then you can apply Collections.binarySearch()
Upvotes: 2