Jumper Jumper - 6 months ago 18
Java Question

Search through array in android

So, I'm trying to have my app search through an array where each object contains multiple values, like so:

public static String name;
public Boolean inUse;
public static Boolean covered;
parkingSpots[] spots = new parkingSpots[9];

spots[0] = new parkingSpots("A1", false, false);
spots[1] = new parkingSpots("A2", false, false);
spots[2] = new parkingSpots("A3", false, false);
spots[3] = new parkingSpots("B1", false, false);
spots[4] = new parkingSpots("B2", false, false);
spots[5] = new parkingSpots("B3", false, false);
spots[6] = new parkingSpots("C1", false, true);
spots[7] = new parkingSpots("C2", false, true);
spots[8] = new parkingSpots("C3", false, true);


What I want it do to is search to see if the spot is both covered and not in use, and then return the name of the first available spot with that criteria, so I did this:

public boolean coveredSearch() {
if (Arrays.asList(spots).contains(covered = true)) {
if (Arrays.asList(spots).contains(inUse = false)) {
return Arrays.asList(spots).contains(name);

}

}


But for some reason, running this method crashes my app. Does anyone know the reason why?

Answer

As said you cannot use contains like that. Contains checks that an element is in a List using the equals() method.

Put this method in your ParkingSpots class. And call it to find your desired spot.

public String coveredSearch(List<ParkingSpots> parkingSpots) {
        for (ParkingSpots p: parkingSpots) {
            if (!p.inUse && p.covered) {
                return p.name;
            }
        }
        return "Cannot find parking space";
    }

Testing:

public class SpacesTest {

    public static void main(String[] args) {

        ParkingSpots ps = new ParkingSpots("Dummy", false, false);

        ParkingSpots[] spots = new ParkingSpots[9];

         spots[0] = new ParkingSpots("A1", false, false);
         spots[1] = new ParkingSpots("A2", false, false);
         spots[2] = new ParkingSpots("A3", false, false);
         spots[3] = new ParkingSpots("B1", false, false);
         spots[4] = new ParkingSpots("B2", false, false);
         spots[5] = new ParkingSpots("B3", false, false);
         spots[6] = new ParkingSpots("C1", false, true);
         spots[7] = new ParkingSpots("C2", false, true); 
         spots[8] = new ParkingSpots("C3", false, true);

         System.out.println(ps.coveredSearch(Arrays.asList(spots)));
    }    
}

Output: C3

Also as said I recommend you rename ParkingSpots to ParkingSpot.

Comments