Home > OS >  Why is this piece of Java code not working? [closed]
Why is this piece of Java code not working? [closed]

Time:09-30

I am doing one of the Java exercises, it ask us to return a list of all ships where the class type matches that of the referenceType parameter. For example, if there is a list with 2 CargoShip, 3 PassengerFerry, and 1 PaddleSteamer and referenceType parameter is a PassengerFerry, then the 3 PassengerFerry objects must be returned in a list. If none of the ships in the list have a matching class type, return an empty (but initialised) ArrayList that holds Ship objects is returned.

This is what I have:

public List<Ship> getShipsWhichMatchType(ArrayList<Ship> ships, Ship referenceType) {
    
    ArrayList<Ship> newLst = new ArrayList<>();
    
    for (int n = 0; n < ships.size(); n  ) {
        Ship shipObj = ships.get(n);
        if (shipObj.getClass().equals(referenceType.getClass())) {
            newLst.add(shipObj);
        }
        return newLst;
    }
    return newLst;
}

However, there is one test that keeps failing:

=> java.lang.AssertionError: If the ship list holds 1 PaddleSteamer, 3 PassengerFerry, 2 CargoShip and the referenceType is a PassengerFerry; then an ArrayList which holds the 3 given PassengerFerry objects must be returned.

expected:<[getclass.PassengerFerry@4920b564, getclass.PassengerFerry@47e75230, getclass.PassengerFerry@43d8de14]>

but was:<[]>

As far as I am concerned, I think the code logic isn't wrong. I don't see which part I have done wrong, since it passed all other 5 tests. That must mean the code I have written can successfully add the particular ship obj into the list and return it. Any hint will be appreciated.

CodePudding user response:

Try the following:

public List<Ship> getShipsWhichMatchType(ArrayList<Ship> ships, Ship referenceType) {
    
    ArrayList<Ship> newLst = new ArrayList<>();
    
    for (int n = 0; n < ships.size(); n  ) {
        Ship shipObj = ships.get(n);
        if (shipObj.getClass().equals(referenceType.getClass())) {
            newLst.add(shipObj);
        }
    }
    return newLst;
}

You are returning the newLst way too soon, basically at the first iteration of your for loop.

CodePudding user response:

First of all, you should consider using the for-each construction of java. And I think your problem is the nested return statement inside the for.

When it is encountering an element , it is checking if it is of correct type and then puts it in the collection. But then it returns with out traversing the other elements

Your other tests succeeded because probably you had only 1 of the referenceObj in the list, which added it and returned

And well, if you want to do just this with the referenceObj, use a Class<? extends Ship> instead and pass the class object while calling the method

  •  Tags:  
  • java
  • Related