1

I have a problem and it's that I try to get the position of an item in an ArrayList called cars.

Car car = new Car(int idcar, String model, String brand);  //Here it's an example

ArrayList<Car> cars = new ArrayList<Car>();

And suppose that I have 5 cars in the ArrayList and I want to get the information of the car number 3 so I tried to get the position with the function indexOf() but it always returns me the value -1.

I know that the value -1 it's when it didn't found any car in the arraylist that it's equals to the car that I use in the function. Could it be because idcar is null when I use the second constructor and try to find the object with indexOf()? I use the function like this:

int position = cars.indexOf(car);

I think it's because I have 2 constructors of the class Car. One with idcar, model and brand and another with just model and brand. I did that because if I don't know the id of the car, I can't use the car in the function so it's an infernal loop and I don't have any idea how to end it.

It's connected to a database that save all the cars that you insert into the arraylist and it's why I need the id, just because if I enter 7 cars one day, close the application and run it again, I won't know the id (that it's the position in the arraylist) of this car and I won't be able to delete one of them, for example.

Of course I have all get's and set's methods in the class Car to get or set all the information when I have inicialized the object Car.

I expect it could be understood clearly.

Thank you very much!

Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
  • 3
    _"I want to get the information of the car number 3 so I tried to get the position with the function indexOf()... "_ why use `indexOf()` if you know what is the index which is `3`? why not just use `cars.get(3)`? – Baby Mar 12 '15 at 02:16

1 Answers1

2

If you haven't implemented Car's equals() method, you have to be sure that you are passing exactly the same instance of Car to the indexOf() method as the instance that is contained by the list.

This is because indexOf() uses contained objects' equals() method and equals() default implementation is just a == comparison.

It'd make sense to implement Car's equals() method.

migron
  • 66
  • 5