I am using the below approach,
public class Solution {
public static void main(String[] args) {
List<Car> cars = new ArrayList<Car>();
cars.add(new Car(1,"A"));
cars.add(new Car(2,"B"));
cars.add(new Car(3,"C"));
cars.add(new Car(4,"D"));
cars.add(new Car(5,"E"));
cars.add(new Car(6,"F"));
if(cars.contains(new Car(4))){
System.out.println(cars.get(cars.indexOf(new Car(4))));
}
}
}
class Car {
int number;
String name;
Car(int number, String name){
this.number = number;
this.name = name;
}
Car(int number){
this.number = number;
}
@Override
public boolean equals(Object obj) {
Car other = null;
if(obj instanceof Car){
other = (Car) obj;
}
return this.number == other.number;
}
@Override
public int hashCode() {
return number;
}
@Override
public String toString() {
return number + " " +name;
}
}
Can anybody please verify and let me know if this approach
cars.get(cars.indexOf(new Car(4)))
Please ignore the Car object I am creating here, That is only for understanding. In my case I need object with only one property to identify the object.
is correct, or if there is any better approach.
Thanks