简体   繁体   English

arraylist:将 object 与字符串进行比较

[英]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.这个 class 的基本目的是定义一个最喜欢的项目 arraylist,在这种情况下是关于汽车的。 The cars objects have a car name and a rating for car 1-5.汽车对象具有汽车名称和汽车 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.我弄乱了将字符串或整数与数组列表中的汽车 object 进行比较的部分。 what is wrong with my equals() method?我的 equals() 方法有什么问题? can contains() method work the same way? contains() 方法可以以同样的方式工作吗?

The numberOfItemsOfRating method allows user to specify rating and hence the method returns the no cars with the rating. numberOfItemsOfRating 方法允许用户指定评级,因此该方法返回没有带有评级的汽车。 the searchForItems method checks if String description specified matches the cars name in array list, and hence returns the car in arraylist. searchForItems 方法检查指定的字符串描述是否与数组列表中的汽车名称匹配,因此返回 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 .您正在根据 object 本身进行相等性检查,而您应该针对object 的属性进行检查 In your particular case you should be looking at the rating attribute of each Car/Item in your collection.在您的特定情况下,您应该查看您收藏中每辆汽车/物品的rating属性。 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.两条快速评论,您应该为您的Item class 实施平等方法。但在这种情况下,这不是问题的实际来源。 Also, you mention cars alot in your code, but your bean class is called 'Item'.此外,您在代码中提到了很多汽车,但您的 bean class 被称为“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.也不要忘记修复您的searchForItem方法,目前您正在测试数组列表与字符串的相等性,该字符串永远不会返回 true。 Correct it in the same way as described above, but using the description attribute of your car, instead of the rating attribute.以与上述相同的方式更正它,但使用您汽车的description属性,而不是rating属性。

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.您的 ArrayList cars (在本例中为整个列表)永远不会等于单个字符串。

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 .如果您想搜索汽车,则需要检查列表中的所有项目,看看它们的名称(或您存储在Item类中的任何信息)是否与给定的description匹配。

This is not the way you should use the equals method, instead I suggest you use or implement Item#getRating() and Item#getDescription() .这不是您应该使用 equals 方法的方式,相反我建议您使用或实现Item#getRating()Item#getDescription() Use cars.get(i).getDescription().equals(description) to check for the description.使用cars.get(i).getDescription().equals(description)检查描述。 To check for the rating use cars.get(i).getRating() == rating .要检查评级,请使用cars.get(i).getRating() == rating

You should not use equals to compare an Item with a string, as this would violate the equals contract .你不应该使用 equals 来比较一个 Item 和一个字符串,因为这会违反 equals 契约

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).equals(al))在这里您将字符串与 object 进行比较,因此使用错误的情况下您可以尝试以下编码

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. getItem() 可能是 cars Class 中名为“item”的变量之一,键入“string”并将其放入 getter 和 setter。

lly if(cars.equals(description)) is wrong. lly if(cars.equals(description)) 是错误的。 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. getDescription() 可能是 cars Class 中名为“description”的变量之一,键入“string”并将其放入 getter 和 setter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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