为什么Collections.frequency为我的收藏返回零?

时间:2018-01-17 23:34:08

标签: java arraylist

有人可以向我解释为了将这些项目添加到我的库存arraylist中我做错了什么?问题是当我用Collections.frequency检查某个项目的库存时,它继续说该项目为零。

private List<Food> inventory = new ArrayList<>();
private double balance = 100.00;

public void startingInv(){
    addFoods(10, Food.HAMBURGER);
    addFoods(10, Food.CHEESEBURGER);
    addFoods(10, Food.HOTDOG);
    addFoods(10, Food.SODA);
    addFoods(10, Food.CHEESIEBOY);
    addFoods(10, Food.WATER);
    addFoods(10, Food.YEET);
}

以上是我尝试将不同类型的食物添加到库存arraylist的方法(我已经调用了我的Food.java类)。

下面是addFoods方法,每次为上面的代码中的每种食物调用它。

    public int addFoods(int amount, int type){
    for (int i = 0; i < amount; i++){
        this.inventory.add(new Food(type));
    }
    return Collections.frequency(inventory, type);
}

2 个答案:

答案 0 :(得分:1)

请注意what the API is actually doing here

  

返回指定集合中等于指定对象的元素数。更正式地,返回集合中元素e的数量,使Objects.equals(o, e)

解决此问题的方法:

  • equals班级
  • 实施Food
  • 实例化Food的实例,其中包含您想要的特定类型
  • 使用Collections.frequency(inventory, instanceOfFoodYouCareAbout)

答案 1 :(得分:1)

您的代码始终返回0,因为inventory包含Food而非Integer类型的元素,所以基本上您尝试比较Integer Food Collections.frequency(inventory, type);对象的Objects.equals(o, e)对象,因此true对于这两种不同的类型永远不会是equals

您可以实施Makoto提及的hashcode / inventory或 在没有实施equals / hashcode的情况下返回return (int)inventory.stream() .filter(f -> f.getType() == type) .count(); 中给定元素频率的替代方法是:

getType

其中type是一个getter,在任何给定的Food实例中返回getType的值。换句话说,您必须在Food类中使用名为type的getter返回testing = sc.parallelize([1,2,3]) testing.saveAsTextFile("Desktop\Testing.txt") 的值。