简体   繁体   中英

arraylist: comparing an object with a string

Hi guys could anyone tell me where im going wrong?

The basic aim of this class is to define a favourite items arraylist which in this case is about cars. The cars objects have a car name and a rating for car 1-5.

how do you see if a string is equal to the car objects rating. im messing up the part where you compare a string or int to an car object in array list. what is wrong with my equals() method? can contains() method work the same way?

The numberOfItemsOfRating method allows user to specify rating and hence the method returns the no cars with the rating. the searchForItems method checks if String description specified matches the cars name in array list, and hence returns the car in arraylist.

here is a glimpse of my two methods with constructors and variables:

public class FavouriteItems
{
    private ArrayList<Item> cars; 

    /**
     * Constructor for objects of class FavouriteItems
     */
    public FavouriteItems()
    {
        cars= new ArrayList<Item>();

    }

    /**
     * Add a new Item to your collection
     * @param newItem The Item object to be added to the collection.
     */
    public void addToFavourites(Item newItem) 
    {
        cars.add(newItem);

    }
    /**
     * Count the number of Items with a given rating 
     * @return The number of Items (Item objects) 
     *          whose rating is rating (could be 0).
     *          If the rating parameter is outside the valid
     *          range 1..5 then print an error message and return 0.
     */
    public int numberOfItemsOfRating(int rating)
    {
        int counter = 0;
        if(rating >= 1 && rating <=5) 
        {
            for ( int i =0; i < cars.size(); i++)
            {
                int num = rating;
                String al = Integer.toString(rating);
                if(cars.get(i).equals(al))
                {
                    counter++;
                }
            }
        }
        else 
        {
            System.out.println("No cars match your ratings");
            counter = 0;
        }
        return counter;
    }

    /**
     * Find the details of a Item given its description
     * @return Item object if its description is in the collection
     * or null if there is no item with that description
     */
    public Item searchForItem(String description) 
    {
         for(int i=0; i<cars.size(); i++)
        { 
            if(cars.equals(description))
            { 
                 return cars.get(i);
            } 
            else 
            { 
                return null;
            }
        }  
      }
} 

You are doing your equality check based off the object itself, when instead you should be doing it against properties of the object . In your particular case you should be looking at the rating attribute of each Car/Item in your collection. Your code would look something like this:

final String ratingStr = Integer.toString(rating);

int counter = 0;
for (for final Item car: cars) {
    if(ratingStr.equals(car.getRating()) {
        ++counter;
}

System.out.println("Number of 'cars' with the rating is: " + counter);

Two quick comments, you should implement equality methods for your Item class. But in this case that is not the actual source of your issues. Also, you mention cars alot in your code, but your bean class is called 'Item'. You might want to reconcile that as it is potentially confusing to others who read your code.

Don't forget to fix your searchForItem method as well, currently you are testing equality of an array list to a string, which will never return true. Correct it in the same way as described above, but using the description attribute of your car, instead of the rating attribute.

cars.get(i)

returns an Item, not a String. So

if(cars.get(i).equals(al))

is not correct.

if(cars.equals(description))

Your ArrayList cars (the whole list in this case) will never equal a single String.

If you want to search for a car, you'll need to check all items in your list and see, if their name (or whatever information you store in the Item -class) matches the given description .

This is not the way you should use the equals method, instead I suggest you use or implement Item#getRating() and Item#getDescription() . Use cars.get(i).getDescription().equals(description) to check for the description. To check for the rating use cars.get(i).getRating() == rating .

You should not use equals to compare an Item with a string, as this would violate the equals contract .

if(cars.get(i).equals(al)) Here you are compare the string with object so it's wrong incase of use that u can try the below coding

if(cars.get(i).getItem().equals(al))

is possible where getItem() one of the variable in cars Class named "item", type as 'string' and put it getter and setter.

lly if(cars.equals(description)) is wrong. here u are trying to compare the list name with string so better to use the below coding

 if(cars.get(i).getDescription().equals(description))
    return cars.get(i);

is possible where getDescription() one of the variable in cars Class named "description", type as 'string' and put it getter and setter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM