Issue
I was wondering if I could get some advice please. I have the following code:
private static int getIndex(String regneeded) {
System.out.println("The reg passed to getIndex method is:" + regneeded);
if (arraylist.contains(regneeded)) {
int pos = arraylist.indexOf(regneeded);
System.out.println("The position of the vehicle in the array list is:" + pos);
}else {return -1;}
return 0;
}
What I am trying to do is search an Array of DeliveryVehicles, for a specific reg number (that I pass to the method) and then say what position in the ArrayList the object that contains this reg is located.
I know I have an issue as I am searching for a string within an ArrayList and what I have in my ArrayList are objects. So, just looking for any advice while I continue to research.
Thank you in advance. Apologies if this is basic I am very new to Java.
EDIT: To include further information on the objects contained in the ArrayList.
DeliveryVehicle objects are contained in the ArrayList. Each contain registration numbers (they have other attributes but I'm focusing on the registration number to understand this issue first). There are setters (setRegNum()) and getters (getRegNum()) in the base class DeliveryVehicle for the registration number, and I pass the registration number to the constructor when I create my vehicle object as follows:
DeliveryBike myVehicle = new DeliveryBike("21D789");
arraylist.add(myVehicle);
I have extended the base class to include a DeliveryBike class (as seen). The code I originally posted was a method in my controller class. So, I suppose I'm confused how to access the registration number within the DeliveryBike object.
Thank you.
Solution
Well, you would have to walk over the DeliveryVehicle
s and check whether the registration number of the object is equal to the registration number you're searching:
int getIndex(String search) {
for (int i = 0; i < arraylist.size(); i++) {
if (Objects.equals(arraylist.get(i).getRegNum(), search)) {
System.out.println("The position of the vehicle in the arraylist is: " + i);
return i;
}
}
return -1;
}
Note that contains
and indexOf
search for a whole object within a list, but they are not suitable for searching for objects with a specific attribute.
For each object in the arraylist
, the attribute registrationNumber
is compared to the string you're search
ing, and if they match, print something to the console and immediately return i
, which is the position of the found element.
Otherwise, return -1
, which is a sentinel value meaning that there is no object with that registration number.
Note that there are data structures which are a better choice for this kind of scenario, like using a Map or Streams, but I don't think that is in scope of the question.
Answered By - MC Emperor
Answer Checked By - Timothy Miller (JavaFixing Admin)