ArrayList and .contains() question
Ok so in another topic I was discussing about how it might be more efficient to use .contains() to search through an arraylist, however I wasn't sure how exactly.
This is entirely hypothetical and here is the code I suggested to search through an arraylist to find an object.
myArray is the array list.
for (int i=0; i<myArray.size();i++)
getName() is a method that returns a string from the object.
location is an inputed string from the user
addMileage() is a method that adds an integer to the objects mileage variable.
So my question is, how could you make this more efficient. While its fine for short arrays, but if I was making an inventory program for a car dealership that had 3000-4000 cars on the lot at any given time this would be rather inefficient as every search would have to go through every car.
This is what Norm suggested, and I am curious for a further explanation.
I suggested to the OP of the previous topic that .contains() might be more efficient but I couldn't figure out how in my head. Is this true? If it is then can someone explain how I would use it in a more efficient manner?
The contains() method uses the equals() method which can look for the same object vs an object with the same contents. With a large number of items, a Map might be a better container for quick look ups.
Or you could override the class's equals() method. That can be tricky if the object is used in some containers that use hashcode.
For student exercises, none of this matters.
Does anyone who has a bit more knowledge than myself have an idea as to how I could make this more efficient?